【问题标题】:Filter Exact word not wholeword过滤确切的单词而不是整个单词
【发布时间】:2014-10-03 10:06:45
【问题描述】:

只想替换数组列表中的确切单词,当前代码工作期望它检查整个单词内容并替换:(

例子:-

$String= 这是一个测试,快乐的测试

它将“testing”替换为 t--ting 并将 test 替换为 t--t

想要输出:- 只过滤测试为 t--t,过滤词包含在其他字符中时忽略

代码

  function filter($string) {            

    $wordlist = array(
                'test' => 't--t'

    );
                   foreach ($wordlist as $word => $filter) {
                        $word = "/{$word}/";
                        preg_match_all($word, $string, $matches);
                            foreach ($matches[0] as $bword) {
                                $pattern = "/{$bword}/";
                                $string = preg_replace($pattern, $filter, $string);
                            } 
                    } 

    return $string;
}

echo filter($string);

我认为模式不正确,可以帮助我找到正确的模式或任何适用的工作代码

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    假设Extract = Exact = 错字?

    如果要匹配确切的单词,请使用word boundaries

    /\btest\b/ 匹配“精确”test。要也匹配无大小写添加iflag:/\btest\b/i

    另请注意,您可以将数组与preg_replace() function 一起使用。所以功能可能是:

    $string= "This is a testing ,Happy test";
    
    function filter($string)
    {            
      $wordlist = array(
      '/\btest\b/' => 't--t'
      );
    
      return preg_replace(array_keys($wordlist), array_values($wordlist), $string);
    }
    
    echo filter($string);
    

    Test at eval.in

    【讨论】:

    • @Randy Suitt 您的输入是 utf-8?比使用 u modifier: /\btest\b/u 注意,如果是这样,模式和输入都必须是 utf-8。或 /\btest\b/ui 用于 utf-8 和无大小写匹配。
    • @RandySuitt 如果在编辑器中输入 ASCII 并输入 UTF-8,则只需对模式进行 utf-8 编码,例如'/\b'.utf8_encode("wörd").'\b/ui'
    • @RandySuitt 因为在 eval.in 上写的代码已经是 UTF-8:比你只需要 '/\bwörd\b/ui' => ' w****' (see example)
    • @RandySuitt 如果你不理解单词边界,你也可以使用否定的lookbehind/ahead 作为替代:/(?<!\w)test(?!\w)/i/(?<!\w)test(?!\w)/ui; \wshorthand 用于单词字符。检查这是否符合您的需求at regex101在右侧,有解释。
    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多