PHP: 编辑内容link

PHP: Edit link in content

我正在尝试将字符串添加到内容中任何 link 的末尾,我正在尝试此代码:

   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

在PHP中,正则表达式需要包含在一对delimiters中。分隔符可以是任何 non-alphanumeric、non-backslash、non-whitespace 字符; /, #, ~ 是最常用的。

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;
}

我猜你在字符串中使用了用作分隔符的字符(即 %)。

你可以用 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);
}