find-and-replace-in-html正则表达式失败

时间:2010-06-29 08:59:05

标签: php html regex

我有一个正则表达式,通过html内容查找过去常用的一些关键字,但现在失败了,我不明白为什么。 (正则表达式来自this thread。)

$find = '/(?![^<]+>)(?<!\w)(' . preg_quote($t['label']) . ')\b/s';
$text = preg_replace_callback($find, 'replaceCallback', $text);

function replaceCallback($match) {
        if (is_array($match)) {
            $htmlVersion = $match[1];
            $urlVersion = urlencode($htmlVersion);
            return '<a class="tag" rel="tag-definition" title="Click to know more about ' . $htmlVersion . '" href="?tag=' . $urlVersion . '">' . $htmlVersion . '</a>';
        }
        return $match;
    }

错误消息指向preg_replace_Callback调用并说:

Warning: preg_replace_callback() [function.preg-replace-callback]: Unknown modifier 't' in /frontend.functions.php  on line 43

1 个答案:

答案 0 :(得分:0)

请注意:这是尝试为正则表达式提供修复程序。正是在这里展示创建一个能够成功解析HTML的正则表达式是多么困难(我敢说不可能)。即使是结构良好的XHTML也会非常困难,但结构不合理的HTML对正则表达式来说是不可取的。

我同意100%使用正则表达式尝试HTML解析是一个非常糟糕的主意。以下代码使用提供的函数来解析一些简单的HTML标记。当它找到嵌套的HTML标记<em>Test<em>

时,它会在第二次尝试时跳闸
$t['label'] = 'Test';
$text = '<p>Test</p>';

$find = '/(?![^<]+>)(?<!\w)(' . preg_quote($t['label']) . ')\b/s';
$text = preg_replace_callback($find, 'replaceCallback', $text);

echo "Find:   $find\n";
echo 'Quote:  ' . preg_quote($t['label']) . "\n";
echo "Result: $text\n";

/* Returns:

Find:   /(?![^<]+>)(?<!\w)(Test)\b/s
Quote:  Test
Result: <p><a class="tag" rel="tag-definition" title="Click to know more about Test" href="?tag=Test">Test</a></p>

*/

$t['label'] = '<em>Test</em>';
$text = '<p>Test</p>';

$find = '/(?![^<]+>)(?<!\w)(' . preg_quote($t['label']) . ')\b/s';
$text = preg_replace_callback($find, 'replaceCallback', $text);

echo "Find:   $find\n";
echo 'Quote:  ' . preg_quote($t['label']) . "\n";
echo "Result: $text\n";

/* Returns:

Find:   /(?![^<]+>)(?<!\w)(Test)\b/s
Quote:  Test
Result: <p><a class="tag" rel="tag-definition" title="Click to know more about Test" href="?tag=Test">Test</a></p>
Warning: preg_replace_callback() [function.preg-replace-callback]: Unknown modifier '\' in /test.php  on line 25
Find:   /(?![^<]+>)(?<!\w)(\<em\>Test\</em\>)\b/s
Quote:  \<em\>Test\</em\>

Result: 

*/

function replaceCallback($match) {
    if (is_array($match)) {
        $htmlVersion = $match[1];
        $urlVersion = urlencode($htmlVersion);
        return '<a class="tag" rel="tag-definition" title="Click to know more about ' . $htmlVersion . '" href="?tag=' . $urlVersion . '">' . $htmlVersion . '</a>';
    }
    return $match;
}