preg_replace除去最后匹配的元素之外的所有内容

问题描述 投票:1回答:1

处理继承的WordPress主题,客户端报告了某些链接的问题。

如果用户添加了3个(示例)链接:

<p><a href="#">Where to Invest</a></p>
<p><a href="#">Where to Invest 2</a></p>
<p><a href="#">Where to Invest 3</a></p>

只有最后一个显示在页面上,查看代码我可以看到内容是通过向锚链接添加类的函数解析的:

function style_content_call_to_action($content, $size='large'){
    $content = preg_replace('/<p><a.*href="(.*)">(.*)<\/a><\/p>/si', '<p><a href="$1" class="object button '.$size.'">$2</a></p>', $content);
    return $content;
}

有没有办法可以调整它以便它适用于所有按钮?除了最后一个并没有删除所有?

谢谢。

php preg-replace
1个回答
2
投票

您需要调整正则表达式模式以使其准确,而不是使用(.*)抓取所有内容:

'/<p><a.*href="([^">]*)">([^<>]*)<\/a><\/p>/i'
© www.soinside.com 2019 - 2024. All rights reserved.