Case insensitive preg_replace_callback

蹲街弑〆低调 提交于 2019-12-02 09:17:20

Simply add the i modifier to your regex to make it perform a case insensitive match:

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

By the way, if you haven't already, you need to escape special regex characters from your keyword. In case any are present, they could screw up your regex and cause PHP warnings/errors. Call preg_quote() before you perform the replacement:

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

Add the "i" modifier to your regexp:

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

Use TOKENregexpTOKENi to perform case-insensitive searches.

See Pattern Modifiers in the PHP manual for full details on modifiers.

Use the /i modifier:

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

You can also use T-Regx library:

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

Also, use of $mykeyword might cause user-input characters to break your pattern. With T-Regx you can use Prepared Patterns and just build your pattern:

<?php
$pattern = Pattern::inject("\b(@keyword)\b", [
    'keyword' => $mykeyword  
    // quoting unsafe characters
]);
$pattern->replace($post->post_content)->callback('doReplace');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!