替换 PHP 中由空格或其他特殊字符分隔的字符串

Replace string that is separated by whitespace or other special character in PHP

我需要找到一种方法来找到文本中的部分字符串并将其替换为 ***

比如我有文字"Jumping fox jumps around the box" 在正常情况下,我会使用:

preg_replace('/\b(fox)\b/i', '****', "fox");

但我想涵盖我们有文本的情况 "Jumping f.o.x jumps around the box""Jumping f o x jumps around the box"

所以基本上,我需要正则表达式来支持那种搜索...覆盖更多特殊字符更好

一种方法是在搜索字符串的每个字符之间添加 class 要忽略的字符。这可以通过简单的 php 函数

来完成
$string = 'Jumping f.o.x jumps around the box';
$word = 'fox';
$ignore = '[\s\.]*';
$regex = '/\b' . join($ignore, str_split($word)) . '\b/i';
$new_string = preg_replace($regex, '***', $string);

如果您的单词包含一些正则表达式特殊字符,您可能需要对每个字符应用 preg_quote

join($ignore, array_map(function($char) {
    return preg_quote($char, '/');
}, str_split($word)));

这是最终函数。

if (! function_exists('preg_replace_word')) {

    function preg_replace_word($search, $replace, $string)
    {
        $ignore = '[\s\._-]*';
        $regex = '/\b' . join($ignore, str_split($search)) . '\b/i';
        return preg_replace($regex, $replace, $string);
    }
}