【问题标题】:php preg_replace href attribute using conditionsphp preg_replace href 属性使用条件
【发布时间】:2015-07-29 00:29:33
【问题描述】:

你好,我有以下标签:

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

这个代码:

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

我想使用上面的代码替换不以 http 或 https 或斜杠开头的 href 标签。
提前致谢。

【问题讨论】:

  • 我已经完成了 80% 的工作,而我的脚本仅使用正则表达式
  • 所以,如果你能帮我用正则表达式做这件事,我将不胜感激
  • 我会处理一些事情,在你的正则表达式中 $1 假设是什么?
  • $1 是为了 (\'|"|) 不是吗?

标签: php regex preg-replace


【解决方案1】:

这样的事情应该可以做到。我建议将来使用解析器How do you parse and process HTML/XML in PHP? 来处理此类任务。这很快就会变得非常混乱。这里还有一个关于这个正则表达式用法的链接,http://www.rexegg.com/regex-best-trick.html

正则表达式:

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

演示: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=("|\')\/?(.*?)\2/', 'href=$2http://website2.com/$3$2', $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=("|')(.*?)\2

演示: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=("|\')\/?(.*?)\2/', 'href=$2http://website2.com/$3$2', $content);

输出:

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

【讨论】:

  • 谢谢你,你能告诉我如何使用它 // 太
  • 如果 href 以 // 开头,则不要替换它
  • 更新了 // 排除以及。
  • 更新不再接受答案?更新有问题?
  • 现在我的代码对所有href都可以正常工作,但是像这样以一个斜杠开头的href
猜你喜欢
  • 2019-01-30
  • 1970-01-01
  • 2019-04-23
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多