如何使用PHP替换包含动态文本的锚标记的URL


How to replace URL with anchor tag contain dynamic text using PHP?

我如何解析或转换链接到适当的<a>链接格式与PHP?

"http://developer.postmarkapp.com/developer-inbound-webhook.html"

这里是什么邮戳JSON API StrippedTextReply响应:

"This is example body with link <http://developer.postmarkapp.com/developer-process-parse.html>"
Possible format:
This is example body with (any link) <http://>
This is example body with <http://> (any link)

预期结果:

'This is example body with <a href="http://developer.postmarkapp.com/developer-process-parse.html">link</a>'

preg_replace()中使用regex将URL替换为锚。正则表达式选择URL并将其替换为锚标记,其中包含href属性中的URL。

preg_replace("/(['w]+)['s]+<([^>]+)>/", "<a href='$2'>$1</a>", $str);

编辑:

如果字符串中锚文本的位置未知(在URL之前或之后),需要使用preg_replace_callback()检查匹配组的值。

preg_replace_callback("/(['w]+)['s]+<([^>]+)>(['w's]+)?/", function($matches){
if (isset($matches[3]))
    return "{$matches[1]} <a href='{$matches[2]}'>{$matches[3]}</a>";
else 
    return "<a href='{$matches[2]}'>{$matches[1]}</a>"; 
}, $str);