Rya*_*yan 1 php replace preg-replace str-replace strip-tags
如何用链接替换标签的内容
$str = 'This <strong>string</strong> contains a <a href="/local/link.html">local link</a>
and a <a href="http://remo.te/link.com">remote link</a>';
$str = strip_tags($str,'<a>'); // strip out the <strong> tag
$str = ?????? // how can I strip out the local link anchor tag, but leave the remote link?
echo $str;
Run Code Online (Sandbox Code Playgroud)
期望的输出:
This string contains a local link and a <a href="http://remo.te/link.com">remote link</a>
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,用其url替换远程链接的内容:
This string contains a local link and a http://remo.te/link.com
Run Code Online (Sandbox Code Playgroud)
我怎样才能达到最终输出?
<a href="(https?://[^"]+)">.*?</a>
$1
Run Code Online (Sandbox Code Playgroud)
<a href="(?!https?://)[^"]+">(.*?)</a>
$1
Run Code Online (Sandbox Code Playgroud)
说明:
这两个表达式匹配<a href=",">和</a>字面.然后,第一个将匹配我们可以引用的捕获组中的远程URL(http可选s,://以及截止的所有内容")$1.第二个表达式将匹配任何不以先前使用的协议开头的内容,然后将链接的实际文本捕获到$1.
请注意,正则表达式不是解析HTML的最佳解决方案,因为HTML不是常规语言.但是,您的用例似乎很"简单",我们可以制作正则表达式.这不适用于像<a href=''></a>或的链接<a href="" title=""></a>,但它可以扩展为允许这些用例(因此我之前的HTML注释不规则).
PHP
$str = 'This <strong>string</strong> contains a <a href="/local/link.html">local link</a> and a <a href="http://remo.te/link.com">remote link</a>';
$str = strip_tags($str,'<a>');
$str = preg_replace('~<a href="(https?://[^"]+)".*?>.*?</a>~', '$1', $str);
$str = preg_replace('~<a href="(?!https?://)[^"]+">(.*?)</a>~', '$1', $str);
echo $str;
// This string contains a local link and a http://remo.te/link.com
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1812 次 |
| 最近记录: |