开发者

What is wrong with this regex?

开发者 https://www.devze.com 2023-01-13 03:16 出处:网络
i need the following - if i have a sentence $str = \"i like programming very much\"; and i search for a word

i need the following -

if i have a sentence

$str = "i like programming very much";

and i search for a word

$word = "r";

i expect it to return the sentence

"i like *p***r***og***r***aming* *ve***r***y* much"

I wrote the following regex for it, but it sometimes do开发者_如何学JAVAesn't work.

$str = preg_replace("/([^\s{".preg_quote($word)."}]*?)(".preg_quote($word).")([^\s{".preg_quote($word)."}]*)/siu","<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",$str);

Could you tell me what i wrote wrong?

Thanks

UPDATE:

for example it doesn't work when

$str = "ameriabank"; and $word = "ab";

...


Why dont't you just use str_replace()? I think it's more simple

$search = "ab";
$word = "ameriabank";
$newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";


$str = "i like programming very much";
$w = "r";
echo preg_replace("/($w)/", "<b>$1</b>", $str);

Output:

i like p<b>r</b>og<b>r</b>amming ve<b>r</b>y much

Answer to the comment: do it in two steps.

$str = "i like programming very much ready tear";
$w = "r";
$str = preg_replace("/\\b((?:\\w+|\\b)$w(\\w+|\\b))\\b/", "<i>$1</i>", $str);
$str = preg_replace("/($w)/", "<b>$1</b>", $str);
echo $str;

output:

i like <i>p<b>r</b>og<b>r</b>amming</i> <i>ve<b>r</b>y</i> much <i><b>r</b>eady</i> <i>tea<b>r</b></i>


visit highlight multiple keywords in search and be amazed.


What about this way :

$str = "i like programming very much";
$word = "r";
$list = explode(' ',$str);
for($i=0; $i<count($list); $i++) {
    if(preg_match("/$word/", $list[$i])) {
        $list[$i] = '<i>'.preg_replace("/$word/siu", "<b>$word</b>", $list[$i]).'</i>';
    }
}
$str = implode(' ',$list);
echo $str,"\n";


$str = "i like programming very much";
$word = "r";
function highlight($matches)
{
    global $word;
    return '<span class="pice1">'.str_replace($word,'<span class="pice2">'.$word.'</span>',$matches[0]).'</span>';
}
echo $str = preg_replace_callback("/([^\s]*?".preg_quote($word, '/')."[^\s]*)/siu", highlight, $str);

do the job(and it works with foreign languages too)...

0

精彩评论

暂无评论...
验证码 换一张
取 消