Jump to content

Regex help replacing text in multiple lines of text file


John_A

Recommended Posts

I have a file in the same location as my PHP file, say test.txt, and in multiple locations it has content like: -

href="http://www.domain.com/entry.php/256/1/this-is-the-title"
or

href="http://www.domain.com/entry.php/123/2/another-title"
 

which I need replaced within the file to: -

href="{EntryNumber=256.link}"
and

href="{EntryNumber=123.link}"
Only the first number is needed for the replacement, it will be between 1 and 999. Everything between the 5th / and the 2nd " can be safely ignored and removed. This is not the only content in the line, and sometimes there may be more than one occurrence per line.

 

I've got this so far: -

$buffer = "";
$fp = file($file);
foreach($fp as $line){
   $buffer .= preg_replace(***struggling with this bit***);
}
fclose($fp);
echo $buffer;
file_put_contents($file, $buffer);
Am I along the right lines generally? And I have no idea what the preg_replace should be as my regex is a bit trial and error, more error in this case...

 

As always, any help greatly appreciated!

 

EDIT: If it matters, the largest file I need to edit is 39Kb, and includes 175 occurrences of the replacements.

Link to comment
Share on other sites

There's no need for file() - take the whole file into a string, run one regex to replace all instances, then send it back to the file.

 

The regex you're looking for could be like

#"http://www.domain.com/entry.php/(\d+)/[^"]+"#
Replace that with

"{EntryNumber=\1.link}"
Use single-quoted strings for those so PHP itself doesn't try to interpret what's in them.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.