0

在下面的函数中,我想匹配关键字不区分大小写(应该匹配“蓝色瑜伽垫”和“蓝色瑜伽垫”)...

但是,它目前仅在关键字相同大小写时才匹配。

$mykeyword = "蓝色瑜伽垫";

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post->post_content);

// the callback function
function doReplace($matches)
{
    static $count = 0;

    // switch on $count and later increment $count.
    switch($count++) {
        case 0: return '<b>'.$matches[1].'</b>';   // 1st instance, wrap in bold
        case 1: return '<em>'.$matches[1].'</em>'; // 2nd instance, wrap in italics
        case 2: return '<u>'.$matches[1].'</u>'; // 3rd instance, wrap in underline
        default: return $matches[1];              // don't change others.
            }
    }
4

5 回答 5

3

只需将i修饰符添加到您的正则表达式,使其执行不区分大小写的匹配:

"/\b($mykeyword)\b/i"

顺便说一句,如果您还没有,您需要从关键字中转义特殊的正则表达式字符。万一存在,它们可能会搞砸您的正则表达式并导致 PHP 警告/错误。preg_quote()在执行更换之前致电:

$mykeyword_escaped = preg_quote($mykeyword, '/');
$post->post_content = preg_replace_callback("/\b($mykeyword_escaped)\b/i","doReplace", $post->post_content);
于 2010-10-29T16:44:55.080 回答
0

将“i”修饰符添加到您的正则表达式:

/\b($mykeyword)\b/i
于 2010-10-29T16:45:38.047 回答
0
$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content);

用于TOKENregexpTOKENi执行不区分大小写的搜索。

有关修饰符的完整详细信息,请参阅PHP 手册中的模式修饰符。

于 2010-10-29T16:45:45.987 回答
0

使用 /i 修饰符:

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content);
于 2010-10-29T16:46:00.277 回答
0

您还可以使用T-Regx 库

<?php
pattern('\b($mykeyword)\b')->replace($post->post_content)->callback('doReplace');
      // ↑ Delimiters are not required 

此外,使用$mykeyword可能会导致用户输入的字符破坏您的模式。使用T-Regx,您可以使用Prepared Patterns构建您的模式:

<?php
$pattern = Pattern::inject("\b(@keyword)\b", [
    'keyword' => $mykeyword  
    // quoting unsafe characters
]);
$pattern->replace($post->post_content)->callback('doReplace');
于 2019-05-12T22:18:03.577 回答