【问题标题】:PHP preg_replace link to get href and anchor text and concatenate it [duplicate]PHP preg_replace链接以获取href和锚文本并将其连接起来[重复]
【发布时间】:2017-06-21 14:55:38
【问题描述】:

我需要一些 php 中的正则表达式操作方面的帮助。

我有字符串,例如

$string = 'This article is about something. If You want more  
<a href='http://www.google.com'>click here</a>. If not just close

我想得到这样的结果:

$string = 'This article is about something. If You want more click here -
http://google.com. If not just close

我如何在 php 中做到这一点?我不能使用简单的 html 解析器和其他库

请帮忙,我不知道如何实现这一点

【问题讨论】:

  • “我不能使用简单的 html 解析器和其他库” ...甚至内置的 DOMDocument 也不行?您可能会在 RegExp 和 HTML 上度过一段糟糕的时光......
  • I cannot use simple html parser and other libraries,为什么不呢?你可以使用preg_replace?如果可以使用,您是否尝试过任何方法?
  • 如果 DOMDocument 在 php 中构建,我会尝试使用它。我错过了。我不能使用外部库。
  • 不惜一切代价避免使用正则表达式解析 HTML。

标签: php html regex parsing


【解决方案1】:

真的找不到一种方法来一步完成这一切,但这应该可行:

<?php
$link = "This article is about something. If You want more <a href='http://www.google.com'>click here</a>. If not just close"; 
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result); // Grab the href
$link = preg_replace("/<a href=.*?>(.*?)<\/a>/",$result[2][0],$link); // remove a tag and replace with href value
echo $link;
// output: This article is about something. If You want more http://www.google.com. If not just close
    ?>  

【讨论】:

  • 谢谢,问题是我真的需要锚文本(点击这里),第二个问题是字符串可以包含多个链接。您的代码将所有链接替换为第一次出现的 href。
猜你喜欢
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 2020-02-10
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
相关资源
最近更新 更多