我正在尝试在内容中的任何链接的末尾添加一个字符串,我尝试使用此代码:
add_filter('the_content', 'crawl_content');
function crawl_content( $text ) {
$search = '/href="(.*?)"/s';
preg_match_all( $search, $text, $matches);
for ($a = 0; $a < count($matches[0]); $a++) {
$new = "href=\"" . $matches[1][$a] . "/?=dddd\" class=\"newsLink\"";
$text = preg_replace('%' . $matches[0][$a] . '%', $new, $text);
}
return $text;
}
问题是:
Warning: preg_replace(): Unknown modifier 'd' in functions.php on line 112
答案 0 :(得分:1)
我猜你在字符串中出现了用作分隔符(即%
)的字符。
您可以使用preg_quote转义它:
// all domains to exclude, separated by |
$domains_to_exclude = 'kam.com|kam2.com';
for ($a = 0; $a < count($matches[0]); $a++) {
if (preg_match('~'.$domains_to_exclude.'~i', $matches[1][$a]) ) continue;
$new = "href=\"" . $matches[1][$a] . "/?=dddd\" class=\"newsLink\"";
$text = preg_replace('%' . preg_quote($matches[0][$a], '%') . '%', $new, $text);
}
答案 1 :(得分:0)
在PHP中,正则表达式需要包含在一对delimiters中。分隔符可以是任何非字母数字,非反斜杠,非空白字符; /,#,〜是最常用的。
function crawl_content($text)
{
$search = '/href="(.*?)"/s';
preg_match_all($search, $text, $matches);
for ($a = 0; $a < count($matches[0]); $a++) {
$new = sprintf('href="%s/?=dddd" class="newsLink"',$matches[1][$a]);
$text = preg_replace('~' . $matches[0][$a] . '~', $new, $text);
}
return $text;
}