Php 这个正则表达式怎么了?

Php 这个正则表达式怎么了?,php,regex,Php,Regex,我需要以下资料- 如果我有一句话 $str = "i like programming very much"; 我在寻找一个词 $word = "r"; 我希望它能返回判决 “我非常喜欢我的生活” 我为它编写了下面的正则表达式,但有时不起作用 $str=preg\u replace(“/([^\s{.preg\u quote($word)。”}]*?)(“.preg\u quote($word)。”)([^\s{.preg\u quote($word)。“}]*)/siu”,“1$2$3”,

我需要以下资料-

如果我有一句话

$str = "i like programming very much";
我在寻找一个词

$word = "r";
我希望它能返回判决

“我非常喜欢我的生活”

我为它编写了下面的正则表达式,但有时不起作用

$str=preg\u replace(“/([^\s{.preg\u quote($word)。”}]*?)(“.preg\u quote($word)。”)([^\s{.preg\u quote($word)。“}]*)/siu”,“1$2$3”,“$str”)

你能告诉我我写错了什么吗

谢谢

更新:

例如,当

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

$str=“我非常喜欢编程”;
$w=“r”;
echo preg_替换(“/($w)/”、“$1”、$str);
输出:

i like p<b>r</b>og<b>r</b>amming ve<b>r</b>y much
我非常喜欢编程
对评论的回答:分两步进行

$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;
$str=“我非常喜欢编程”;
$w=“r”;
$str=preg_replace(“/\\b((?:\\w+\\b)$w(\\w+\\b))\\b/”,“$1”,$str);
$str=preg_replace(“/($w)/”、“$1”、$str);
echo$str;
输出:

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>
我非常喜欢编程

为什么不直接使用str_replace()?我觉得更简单

$search = "ab";
$word = "ameriabank";
$newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";
$search=“ab”;
$word=“美国银行”;
$newstr=“”.str_替换($search,$word,““$search”。访问并感到惊讶。

这样做怎么样:

$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=“我非常喜欢编程”;
$word=“r”;
$list=explode(“”,$str);
对于($i=0;$i
$str=“我非常喜欢编程”;
$word=“r”;
功能突出显示($matches)
{
全球$字;
返回'.str_replace($word,'.$word.'',$matches[0])';
}
echo$str=preg\u replace\u回调(“/([^\s]*?”。preg\u quote($word,“/”)。“[^\s]*)/siu”,突出显示,$str);

做这项工作(而且它也适用于外语).

你到底想做什么?你想突出显示包含给定子字符串的单词吗?这似乎是它的要点,而且人们似乎普遍希望解决这个问题。我认为以前已经解决了。搜索“突出显示”“我相信你会得到很多好的答案。在这个例子中,我已经展示了我的期望。如果它包含sub_单词,我需要突出显示整个单词,但以其他方式突出显示sub_单词,然后再突出单词的其他部分。如示例所示(参见单词编程)…位置:@shamittomar他们做另一件事。我需要在每个包含关键字的单词中突出显示两种类型。word
编程的其他部分如何?我也需要突出显示它们,但以其他方式(我的意思不是粗体)。。。
$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);