問題描述
我試圖在我的內(nèi)容中匹配 <a>
標(biāo)簽,并將它們替換為鏈接文本,后跟方括號中的 url 用于打印版本.
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.
如果只有href",則以下示例有效.如果 <a>
包含另一個屬性,則匹配太多并且不會返回所需的結(jié)果.
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.
如何匹配 URL 和鏈接文本,僅此而已?
How can I match the URL and the link text and that's it?
這是我的代碼:
<?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;
?>
想要的結(jié)果:
<strong>This is a text link </strong> [http://www.website.com]
推薦答案
您可以使用 ?
使匹配變得不貪婪.您還應(yīng)該考慮到 href
屬性之前可能有一些屬性.
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);
這篇關(guān)于將可點擊的錨標(biāo)簽轉(zhuǎn)換為 html 文檔中的純文本的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!