【问题标题】:Replace string that is separated by whitespace or other special character in PHP替换PHP中由空格或其他特殊字符分隔的字符串
【发布时间】:2018-04-27 23:39:26
【问题描述】:

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

例如,我有文字"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"

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

【问题讨论】:

  • 然后使用'/\bf\W*o\W*x\b/i'

标签: php regex laravel preg-replace preg-match


【解决方案1】:

一种方法是在搜索字符串的每个字符之间添加要忽略的字符的类。这可以通过简单的 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)));

【讨论】:

  • 不错。在这部分中包含 _ 或 - 的正则表达式是什么?
  • 只需将字符添加到忽略类[\s\._-](请记住,- 具有特殊含义,必须转义或放置在末尾/开头)
  • 知道了...当 f.o.x 是 f.ox 或 fo.x(也可以是另一个字符)时,我有问题,你能帮我解决这个问题吗?
  • + 替换为*
【解决方案2】:

这是最终功能。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2013-11-03
    相关资源
    最近更新 更多