代码之家  ›  专栏  ›  技术社区  ›  Simon

这个正则表达式怎么了?

  •  0
  • Simon  · 技术社区  · 16 年前

    我需要以下-

    $str = "i like programming very much";
    

    我在找一个词

    $word = "r";
    

    我希望它能返回这个句子

    我为它编写了下面的regex,但有时不起作用。

    $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);

    更新:

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

    ...

    5 回复  |  直到 16 年前
        1
  •  3
  •   Tokk    16 年前

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

    $search = "ab";
    $word = "ameriabank";
    $newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";
    
        2
  •  2
  •   Amarghosh    16 年前
    $str = "i like programming very much";
    $w = "r";
    echo preg_replace("/($w)/", "<b>$1</b>", $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;
    

    输出:

    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>
    
        3
  •  1
  •   Community Mohan Dere    9 年前

    参观 highlight multiple keywords in search 并且感到惊讶。

        4
  •  1
  •   Toto    16 年前

    $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";
    
        5
  •  0
  •   Simon    16 年前
    $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);
    

    做这项工作(它也适用于外语)。。。