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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3426265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:42:11  来源:igfitidea点击:

PHP string replace match whole word

phpstringreplacestr-replace

提问by NVG

I would like to replace just complete words using php

我想用 php 替换完整的单词

Example : If I have

示例:如果我有

$text = "Hello hellol hello, Helloz";

and I use

我用

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

The new text should look like

新文本应如下所示

NEW hello1 hello, Helloz

NEW hello1 你好,Helloz

PHP returns

PHP 返回

NEW hello1 hello, NEWz

NEW hello1 你好,NEWz

Thanks.

谢谢。

回答by Lethargy

You want to use regular expressions. The \bmatches a word boundary.

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

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


If $textcontains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:

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

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

回答by sandeep kumar

multiple word in string replaced by this

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

    $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.

回答by mario

Arrayreplacement list: In case your replacement strings are substituting each other, you need preg_replace_callback.

数组替换列表:如果替换字符串相互替换,则需要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
);

Obviously / for efficiency /\w+/could be replaced with a key-list /\b(one|two|three)\b/i.

显然 / 为了效率/\w+/可以替换为 key-list /\b(one|two|three)\b/i

回答by Danon

You can also use T-Regxlibrary, that quotes $or \characters while replacing

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

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');