37

我想用php替换完整的单词

示例:如果我有

$text = "Hello hellol hello, Helloz";

我用

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

新文本应如下所示

新 hello1 你好,Helloz

PHP 返回

新你好1你好,NEWz

谢谢。

4

4 回答 4

73

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

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

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

$text = preg_replace('/\bHello\b/u', 'NEW', $text);
于 2010-08-06T17:43:53.670 回答
7

字符串中的多个单词被此替换

    $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;
    Result: Our Members are committed to delivering quality service to both buyers and sellers.
于 2017-04-04T08:30:39.520 回答
2

数组替换列表:如果您的替换字符串相互替换,您需要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+/,可以用 key-list 代替/\b(one|two|three)\b/i

于 2017-11-23T17:46:17.297 回答
0

您还可以使用T-Regx库,在替换时引用$\字符

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');
于 2018-12-12T17:26:54.583 回答