Jump to content

Regex help replacing text in multiple lines of text file


Go to solution Solved by darklexus2k9,

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.

Edited by John_A

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.
  • Solution

i think what you want todo is really easy and can be done with one simple line of regex

 

preg_replace("/href=\"http:\/\/www.domain.com\/entry.php\/(.*?)\/(.*?)\"/", "href="{EntryNumber=$01.link}"", $input_data);


you can see this working at the following link : http://www.phpliveregex.com/p/jGr

Edited by darklexus2k9
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.