将可点击的锚标签转换为HTML文档中的纯文本 [英] Convert clickable anchor tags to plain text in html document
问题描述
我正在尝试在我的内容中匹配< a>
标记,并用链接文本和方括号中的URL替换文本,以供印刷版使用。 / p>
如果仅存在 href,则以下示例有效。如果< a>
包含另一个属性,则它匹配得太多,并且不会返回所需的结果。
我该如何
这是我的代码:
<吗? php
$ content ='< a href =" http://www.website.com">这是文本链接< / a>';
$ result = preg_replace('/< a href ="(http:\ / \ / [A-Za-z0-9\\。:\ /] {1,}) "([[ssS] *?)< / a> /',
'< strong> \\2< / strong> [\ \\1]',$ content);
echo $ result;
?>
所需结果:
< strong>这是文本链接< / strong> [http://www.website.com]
您可以使用?
将匹配设置为不满意。
您还应该考虑 href
属性之前可能存在的属性。
$ result = preg_replace('/< a [^>] *?href =(http:\ / \ / [A-Za-z0-9\\。:\ \ /] +?)>(([\\s\\S] *?)< / a> /',
'< strong> \\2< / strong> [\\1]',$ content);
I am trying to match <a>
tags within my content and replace them with the link text followed by the url in square brackets for a print-version.
The following example works if there is only the "href". If the <a>
contains another attribute, it matches too much and doesn't return the desired result.
How can I match the URL and the link text and that's it?
Here is my code:
<?php
$content = '<a href="http://www.website.com">This is a text link</a>';
$result = preg_replace('/<a href="(http:\/\/[A-Za-z0-9\\.:\/]{1,})">([\\s\\S]*?)<\/a>/',
'<strong>\\2</strong> [\\1]', $content);
echo $result;
?>
Desired result:
<strong>This is a text link </strong> [http://www.website.com]
You can make the match ungreedy using ?
.
You should also take into account there may be attributes before the href
attribute.
$result = preg_replace('/<a [^>]*?href="(http:\/\/[A-Za-z0-9\\.:\/]+?)">([\\s\\S]*?)<\/a>/',
'<strong>\\2</strong> [\\1]', $content);
这篇关于将可点击的锚标签转换为HTML文档中的纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!