Sunday, 15 February 2015

regex - How do I use PHP preg_replace with the same pattern, when the word happens multiple times? -



regex - How do I use PHP preg_replace with the same pattern, when the word happens multiple times? -

sorry question horribly worded, have no thought how state question. easier me show code , explain.

i trying write function allow tagging of words. have database of words phone call glossary. want take big amount of text , multiple instance of [g]some word/words here[/g]. want replace <a href="viewglossary.php?word={word/words between [g][/g]}">{word/words between [g][/g]}</a>

here current function:

function getglossary($str) { $patterns = array(); $patterns[]='/\[g\](.*)\[\/g\]/'; $replacements = array(); $replacements[]='<a href="viewglossary.php?word=$1">$1</a>'; homecoming preg_replace($patterns, $replacements, $str); } echo getglossary($txt);

if single instance of [g][/g] tag works.

$txt='what need know [g]beans[/g]';

this output

what need know <a href="viewglossary.php?word=beans">beans</a>

however this

$txt='what need know [g]beans[/g] , [g]corn[/g]';

will output

what need know <a href="viewglossary.php?word=beans[/g] , [g]corn">beans[/g] , [g]corn</a>

i sure have wrong in pattern. help appreciated.

you need create dot-star lazy: .*?

without ? maintain .* in check, .* eat characters final [/g] the * quantifier greedy, .* starts off matching characters in string end. backtracks far needed allow [/g] match (therefore, backtracks lastly [/g]). the ? makes quantifiers "lazy", match far needed rest of regex match. hence match first [/g].

modify regex so:

$pattern = "~\[g\](.*?)\[/g\]~";

note create regex easier read, have changed delimiter , unescaped forwards slash, there no need escapes slashes unless delimiter slash. mutual delimiters include ~, %, @, #... tildes beautiful. :)

reference

the many degrees of regex greed repetition star , plus

php regex preg-replace

No comments:

Post a Comment