繁体   English   中英

使用preg_replace将自定义标签替换为锚标签

[英]Replace custom tag with anchor tag using preg_replace

我想将<cast>Test Cast</cast>替换为<a href="www.example.com/cast/test-cast">Test Cast</a>

function replace_synopsis_tags($short_synopsis) {

        $pattern = '/<cast>(.+?)<\/cast>/i';
        $replacement = "<a href='".base_url()."casts/".str_replace(" ","-",strtolower("$1"))."'>$1</a>";
        $short_synopsis = preg_replace($pattern, $replacement, $short_synopsis);


        return $short_synopsis;
    }

    $synopsis = "<cast>Test Cast</cast>";
    echo replace_synopsis_tags($synopsis);

返回的是<a href="www.example.com/cast/Test Cast">Test Cast</a>

我该如何解决?

您可以使用DOMDocument,它的工作效率更高。

在线评估: https : //3v4l.org/0l9hT

$html = "
<!DOCTYPE html>
<html>
<body>
<cast>cast-test</cast>
<cast>cast two !</cast>
</body>
</html>";

function castTags(string $html)
{
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    libxml_clear_errors();
    $casts = $dom->getElementsByTagName('cast');
    while($cast = $casts->item(0)) {
        $value = $cast->nodeValue;
        $link = $dom->createElement('a');
        $link->setAttribute('href', "www.example.com/cast/" . rawurlencode(str_replace(' ','-',strtolower($value))));
        $link->nodeValue = $value;
        $cast->parentNode->replaceChild($link, $cast);
    }
    return $dom->saveHTML();
}

echo castTags($html); 
// <!DOCTYPE html> 
// <html>
//     <body>
//         <a href="www.example.com/cast/cast-test">cast-test</a>
//         <a href="www.example.com/cast/cast-two-%21">cast two !</a>
//     </body>
// </html>

如果您使用的是PHP 5.5或更低版本,则只需添加\\e修饰符,脚本便可以正常工作。 但是,如果您使用的是PHP 7,则需要改用preg-replace-callback() PHP 7不再支持\\e修饰符。

您的脚本可以更新为使用preg_replace_callback()以与PHP 7兼容:

function replace_synopsis_tags($short_synopsis) {

    $pattern = '/<cast>(.+?)<\/cast>/i';
    $replacement = function($matches) { return "<a href='".base_url()."casts/".str_replace(" ","-",strtolower($matches[1]))."'>".$matches[1]."</a>"; };
    $short_synopsis = preg_replace_callback($pattern, $replacement, $short_synopsis);

    return $short_synopsis;
}

$synopsis = "<cast>Test Cast</cast>";
echo replace_synopsis_tags($synopsis);

preg-replace的变更日志中:

从PHP 5.5.0 开始 ,传入“ \\ e”修饰符时会发出E_DEPRECATED级别错误。 从PHP 7.0.0起,在这种情况下会发出E_WARNING ,而“ \\ e”修饰符无效。

在PHP 5.4中,您可以使用以下模式:

$pattern = '/<cast>(.+?)<\/cast>/ie'; // with trailing e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM