Replacing a string in a file with another string.

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

New php-forum User
New php-forum User
Posts: 2
Joined: Tue Apr 01, 2003 1:01 pm

Replacing a string in a file with another string.

Postby quiknot » Tue Apr 01, 2003 1:10 pm

Hello, I have a quick question.

I need to be able to open a file, search through it until I find a string, and then replace that string with a new one. I am somewhat new to PHP so I thought I could get some help here.

The variables are:
$info_string_old //Find this string in file
$info_string //Replace with this string

The file name is:

First post, please be nice :D

New php-forum User
New php-forum User
Posts: 2
Joined: Mon Mar 31, 2003 9:00 pm

Postby HighOrbit » Wed Apr 02, 2003 6:15 pm

I think you probably need to do several steps to get what you want here.

to open and read a file you need to use fopen() and fread() to push the file contents into a string.

Once the contents are in the string, you can use regular expression functions like ereg_replace() or preg_replace() to search through the string for a pattern and replace that pattern with a new one.

if you want to write the new data back to the file, then use fwrite() and then fclose() to finish up.

The regular expression part is probably going to be the hard piece. Regular expressions can be complicated depending on the level of complexity of the patterns working with.

User avatar
Posts: 830
Joined: Tue Jan 21, 2003 10:42 pm
Location: Michigan USA

Postby Redcircle » Wed Apr 02, 2003 6:22 pm

str_replace also works nice.

User avatar
New php-forum User
New php-forum User
Posts: 7
Joined: Mon Apr 07, 2003 8:00 pm
Location: Vietnam

Passwd change

Postby quantm » Wed Apr 09, 2003 6:59 pm

I have wrote a function to replace an user password in passwd file under linux as follows:

function replace_passwd_full($filename,$username,$newpasswd)
$separator = ":";
if (!($pipe = fopen($filename, "w"))) {
return false;
for($line=0;$line<$size;$line++) {
$dataline = $data[$line];
$dataline= preg_replace("/".$username.":(\S+):/i", $username.":".$newpasswd.":\$3", $dataline);
return true;

Hope that helps!! :roll: :wink:

Return to “PHP coding => General”

Who is online

Users browsing this forum: No registered users and 3 guests