PHP字符串替换匹配整个单词

时间:2010-08-06 17:37:39

标签: php string replace str-replace

我想用php替换完整的单词

示例: 如果我有

$text = "Hello hellol hello, Helloz";

我用

$newtext = str_replace("Hello",'NEW',$text);

新文字看起来应该是

  

NEW hello1 hello,Helloz

PHP返回

  

NEW hello1 hello,NEWz

感谢。

4 个答案:

答案 0 :(得分:57)

您想要使用正则表达式。 \b匹配单词边界。

$text = preg_replace('/\bHello\b/', 'NEW', $text);

如果$text包含UTF-8文本,则必须添加Unicode修饰符“u”,以便非拉丁字符不会被误解为字边界:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);

答案 1 :(得分:5)

字符串中的多个单词替换为

    $String = 'Team Members are committed to delivering quality service for all buyers and sellers.';
    echo $String;
    echo "<br>";
    $String = preg_replace(array('/\bTeam\b/','/\bfor\b/','/\ball\b/'),array('Our','to','both'),$String);
    echo $String;

答案 2 :(得分:1)

数组替换列表:如果您的替换字符串互相替换,则需要preg_replace_callback

$pairs = ["one"=>"two", "two"=>"three", "three"=>"one"];

$r = preg_replace_callback(
    "/\w+/",                           # only match whole words
    function($m) use ($pairs) {
        if (isset($pairs[$m[0]])) {     # optional: strtolower
            return $pairs[$m[0]];      
        }
        else {
            return $m[0];              # keep unreplaced
        }
    },
    $source
);

显然/效率/\w+/可以替换为键列表/\b(one|two|three)\b/i

答案 3 :(得分:0)

您还可以使用T-Regx库,该库在替换时用@app.route('/update') def update(): c = get_db().cursor() # this just gets the data from the db c = get_db().cursor() c.execute('SELECT GENUS, SPECIES, COMNAME FROM FLOWERS') genus_flowers = c.fetchall() return render_template("update.html", genus_flowers=genus_flowers) $字符

\