HuggieBear Posted August 17, 2007 Share Posted August 17, 2007 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 More sharing options...
HuggieBear Posted August 19, 2007 Author Share Posted August 19, 2007 *bump* Anyone have any ideas, or should I try re-phrasing the question for a better response? Regards Huggie Link to comment https://forums.phpfreaks.com/topic/65396-solved-text-replace/#findComment-327992 Share on other sites More sharing options...
MadTechie Posted August 19, 2007 Share Posted August 19, 2007 set the limit to 1 $nfs = preg_replace($matches[1],$textareas,$fs, 1); limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). Link to comment https://forums.phpfreaks.com/topic/65396-solved-text-replace/#findComment-327993 Share on other sites More sharing options...
HuggieBear Posted August 19, 2007 Author Share Posted August 19, 2007 Thanks Mad, I completely missed that when looking at the manual, I saw the count parameter and thought "That's not what I want". Regards Huggie Link to comment https://forums.phpfreaks.com/topic/65396-solved-text-replace/#findComment-327994 Share on other sites More sharing options...
MadTechie Posted August 19, 2007 Share Posted August 19, 2007 easy to miss Link to comment https://forums.phpfreaks.com/topic/65396-solved-text-replace/#findComment-327996 Share on other sites More sharing options...
plutomed Posted August 19, 2007 Share Posted August 19, 2007 Is this topic solved? Link to comment https://forums.phpfreaks.com/topic/65396-solved-text-replace/#findComment-328029 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.