让我们像[n]个链接一样拥有这样的php string
:
This is a text with a link to [LINK]https://website.com/page/subpage/id This is the text to display[/LINK] and another link to [LINK]https://website2.com/page/subpage/subsubpage/subsubsubpage This is the text to display for link 2[/LINK]. Wow!"
如何将[LINK]和[/ LINK]替换为a href
并显示链接的文字?
Lik this:<a href="https://website.com/page/subpage/id" target="_blank">This is the text to display</a>
我已经尝试preg_replace
但是无法理解它,因为它是超级怪人!
答案 0 :(得分:1)
<?php
$str='This is a text with a link to [LINK]https://website.com This is the text to display[/LINK] and another link to [LINK]https://website2.com This is the text to display for link 2[/LINK]. Wow!';
$pattern='/\[LINK\]([\w:\/\.]+) ([^(\[\/LINK\])]+)\[\/LINK\]/';
echo preg_replace($pattern, '<a href="${1}" target="_blank">${2}</a>', $str) ;
?>
输出
This is a text with a link to <a href="https://website.com" target="_blank">This is the text to display</a> and another link to <a href="https://website2.com" target="_blank">This is the text to display for link 2</a>. Wow!