php preg_replace href 属性使用条件

php preg_replace href attribute using conditions

你好我有以下标签:

$content ='<a href="http://website.com/" />
    <a href="/link1" />
    <a href="https://website.com" />
    <a href="link1" />';

和此代码:

preg_replace('~href=(\'|"|)(.*?)(\'|"|)(?<!\/|http:\/\/|https:\/\/)~i',  'href=http://website2.com/', $content);

我想使用上面的代码替换不以 http 或 https 或斜杠开头的 href 标签。
在此先感谢。

像这样的东西应该可以做到。我建议以后使用解析器,How do you parse and process HTML/XML in PHP?, for tasks such as this though. This can become very messy quickly. Here's a link on this regex usage as well, http://www.rexegg.com/regex-best-trick.html

正则表达式:

/href=("|')https?:\/\/(*SKIP)(*FAIL)|href=("|')(.*?)/

演示:https://regex101.com/r/cV2xB5/1

PHP 用法:

$content ='<a href="http://website.com/" />
    <a href="/link1" />
    <a href="https://website.com" />
    <a href="link1" />';
echo preg_replace('/href=("|\')https?:\/\/(*SKIP)(*FAIL)|href=("|\')\/?(.*?)/', 'href=http://website2.com/', $content);

输出:

<a href="http://website.com/" />
    <a href="http://website2.com/link1" />
    <a href="https://website.com" />
    <a href="http://website2.com/link1" />

更新,用于//排除

使用:

href=("|')(?:https?:)?\/\/(*SKIP)(*FAIL)|href=("|')(.*?)

演示:https://regex101.com/r/cV2xB5/2

PHP:

$content ='<a href="//website.com/" />
    <a href="/link1" />
    <a href="https://website.com" />
    <a href="link1" />';
echo preg_replace('/href=("|\')(?:https?:)?\/\/(*SKIP)(*FAIL)|href=("|\')\/?(.*?)/', 'href=http://website2.com/', $content);

输出:

<a href="//website.com/" />
    <a href="http://website2.com/link1" />
    <a href="https://website.com" />
    <a href="http://website2.com/link1" />