Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Replacing a string in a file with another string.

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

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:
file_info


First post, please be nice :D
quiknot
New php-forum User
New php-forum User
 
Posts: 2
Joined: Tue Apr 01, 2003 1:01 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.

http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fread.php

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.
http://www.php.net/manual/en/ref.regex.php

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

http://www.php.net/manual/en/function.fwrite.php
http://www.php.net/manual/en/function.fclose.php

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.
HighOrbit
New php-forum User
New php-forum User
 
Posts: 2
Joined: Mon Mar 31, 2003 9:00 pm

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

str_replace also works nice.
User avatar
Redcircle
Moderator
Moderator
 
Posts: 830
Joined: Tue Jan 21, 2003 10:42 pm
Location: Michigan USA

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 = ":";
$data=file($filename);
if (!($pipe = fopen($filename, "w"))) {
return false;
}
$size=count($data);
for($line=0;$line<$size;$line++) {
$dataline = $data[$line];
$dataline= preg_replace("/".$username.":(\S+):/i", $username.":".$newpasswd.":\$3", $dataline);
fputs($pipe,$dataline);
}
fclose($pipe);
return true;
}

Hope that helps!! :roll: :wink:
User avatar
quantm
New php-forum User
New php-forum User
 
Posts: 7
Joined: Mon Apr 07, 2003 8:00 pm
Location: Vietnam


Return to PHP coding => General

Who is online

Users browsing this forum: Baidu [Spider] and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron