Jump to content

[SOLVED] Text replace


HuggieBear

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.

 

<?php
$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:

 

<?php
/*
* $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);
?>

 

Regards

Huggie

Link to comment
https://forums.phpfreaks.com/topic/65396-solved-text-replace/
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.