php - Modify regex in a script that highlights certain words in a text by adding span classes to them -
i working on code highlights words, using regex.
here is:
function addregex($word){ return "/\b(\w+)?".$word."(\w+)?\b/i"; } function highlight($word){ return "<span class=\"highlighted\">".$word[0]."</span>"; } function customhighlights($searchstring,$tohighlight){ $searchfor = array_map('addregex',$tohighlight); $result = preg_replace_callback($searchfor,'highlight',$searchstring); return $result; }
lets use function customhighlights searc word "car" in text:
using boundary - \b - method, script searches word car in text.
in regex, have added (\w+)? in front , after word, script match words contain "car" - cars, sportcars, etc...
the problem is, messes inner html, example:
this great car. click here <a href="http://cars.com">more</a>
the script match word car in url of link above, adding span classes , messing html.
how modify regex , avoid this?
use regular expression searches word after last >
or beginning of text, part between , word may not contain tag start <
.
see codepad
code
<?php $str = 'this great car. click here <a href="http://cars.com">more cars</a>'; $word = 'car'; $exp = "/((^|>)[^<]*)(\b(\w+)?".$word."(\w+)?\b)/i"; $repl = "\\1<span class=\"highlighted\">\\3</span>"; var_dump(preg_replace($exp, $repl, $str)); ?>
output
string(141) "this great <span class="highlighted">car</span>. click here <a href="http://cars.com">more <span class="highlighted">cars</span></a>"
Comments
Post a Comment