Jump to content

[SOLVED] Text replace


Recommended Posts

I have two paragraphs on a page that I want to replace.  I've used preg_match_all() to get these paragraphs into an array.  This works without issue and was simple as the paragraphs are between HTML comments.  The code's shown below.


$pattern = '/<!\-{2}\s#CONTENT[^>]+>((?:.(?!<!))+.)<!\-{2}\s#CONTENT[^>]+>/s';
$c = preg_match_all($pattern, $fs, $matches, PREG_PATTERN_ORDER);


I also have the text that I want to replace it with in an array.  I thought it would be a case of simply using preg_replace() or str_replace() with my two array's as arguments to swap them around.  This works without issue too, brilliant.


BUT... And there's always a but.


If the paragraphs are the same, this causes problems.  It replaces both paragraphs, with the the first element in the replacements array, as I would expect it to.  My question is, how can I get each replacement to only replace one instance of the matched text?


Here's the code:


* $matches[1] is my array from preg_match_all()
* $textareas is my array of replacements
foreach ($matches[1] as $k => $v){
   $matches[1][$k] = '/\Q' . $v . '\E/'; // Make each match a valid regex pattern
$nfs = preg_replace($matches[1],$textareas,$fs);




Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

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

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.