【发布时间】:2010-11-02 12:29:33
【问题描述】:
下面的脚本采用 $myContent 块并对 $myKeyword 值执行 doReplace() 函数。我遇到的问题是它不知道替换文本是否已经在标签内。
我需要修改 doReplace() 函数,使其不会触及命名标签(h1、h2、h3、i、u、b、strong、em、img)内部或作为其属性的任何文本。
我认为将其转换为 xPath 方法并寻找有关如何使用 xPath 完成它的建议会更好。所以问题是:“如何将其转换为 xPath”?
注意:替换函数中有 count 变量,因为我只替换关键字的前三个出现。第一次出现时加粗,下一次变为斜体,第三次出现时加下划线。
$myKeyword = "test keyword";
$myContent = "My content contains the "test keyword".
Don't do the replace if the test keyword is inside:
h1, h2, h3, i, u, b, strong, em, tags.
<h1>This test keyword would not be replaced</h1>";
$myContent = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $myContent);
function doReplace($matches)
{
static $count = 0;
switch($count++) {
case 0: return ' <b>'.trim($matches[1]).'</b>';
case 1: return ' <em>'.trim($matches[1]).'</em>';
case 2: return ' <u>'.trim($matches[1]).'</u>';
default: return $matches[1];
}
}
【问题讨论】:
-
这个问题不清楚。向我们展示源 XML 并展示想要的结果。什么是
$matches?。请给我们看一个真实的例子。格式化你的代码,这样就不需要水平滚动——因为它现在很难阅读和理解。 -
@Dimitre - 我已经重新格式化了代码。源将是 $myContent 并将通过 loadHTML 加载
标签: php xslt preg-replace xquery