首页 > 解决方案 > preg_replace_callback(): 未知修饰符 '/'

问题描述

我需要搜索并突出显示这个词。

我的句子是

Please see our Author Guide for more information: http://digital-library.theiet.org/journals/author-guide.
you will be contacted shortly asking you to take a decision and sign either a copyright or Open Access licence form.

我的代码

function find_highlight_word($word) {
        $text = preg_replace_callback($word, function($matches) use (&$counter) {

            $counter++;
            return '<b class="search_mark highlighted" id="matched_' . $counter . '">'
                    . substr($matches[0], 0, strlen($matches[0]))
                    . '</b>';
        }, $text);

        return $text;
}
$word = '//';
$word = '/' . preg_quote($word) . '/i';
$this->find_highlight_word($word);

当我用“ // ”搜索时,显示 php 错误。

标签: php

解决方案


您正确地尝试对字符串进行预引用,但您没有告诉它您的分隔符是什么,因此//字符串内部会导致问题。将使用的分隔符作为第二个参数传递,因此也可以对其进行转义:

$word = '/' . preg_quote($string, '/') . '/i';

推荐阅读