将可点击的锚标签转换为HTML文档中的纯文本 [英] Convert clickable anchor tags to plain text in html document

查看:64
本文介绍了将可点击的锚标签转换为HTML文档中的纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的内容中匹配< 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆