我想通过链接替换单词组。我使用多维数组来定义这些(在现实世界中将有数千个)。 这是代码:
$text = "<html><body><pre>
Here is Foo in text.
Now come Baz? and Bar-X.
Replace nothing here: Foo (followed by brackets).
</pre></body></html>";
$s = array(
array("t" => "Foo", "u" => "http://www.foo.com", "c" => "foo"),
array("t" => "Baz?", "u" => "http://www.baz.net", "c" => "test"),
array("t" => "Bar-X", "u" => "http://www.baz.org", "c" => "test")
);
foreach ($s as $i => $row) {
$replaced = preg_replace('/(?=\Q'.$row["t"].'\E[^(]+$)\b\Q'.$row["t"].'\E\b/m',
'<a href="'.$row["u"].'" class="'.$row["c"].'">'.$row["t"].'</a>',
$text);
}
echo $replaced;
?>
问题是只替换了一个数组元素,而不是全部。这是关于peg_replace()中$ text的内容。有人给我一个暗示吗?谢谢!
答案 0 :(得分:1)
你必须添加到$replaced
var,现在你要覆盖变量。
<?php
$text = "<html><body><pre>
Here is Foo in text.
Now come Baz? and Bar-X.
Replace nothing here: Foo (followed by brackets).
</pre></body></html>";
$s = array(
array("t" => "Foo", "u" => "http://www.foo.com", "c" => "foo"),
array("t" => "Baz?", "u" => "http://www.baz.net", "c" => "test"),
array("t" => "Bar-X", "u" => "http://www.baz.org", "c" => "test")
);
$replaced = $text;
foreach ($s as $i => $row) {
$replaced = preg_replace('/(?=\Q'.$row["t"].'\E[^(]+$)\b\Q'.$row["t"].'\E\b/m',
'<a href="'.$row["u"].'" class="'.$row["c"].'">'.$row["t"].'</a>',
$replaced );
}
echo $replaced;
?>