如何使用 PHP 将 URL 替换为包含动态文本的锚标记?
How to replace URL with anchor tag contain dynamic text using PHP?
如何使用 PHP 将 link 解析或转换为正确的 <a>
link 格式?
"http://developer.postmarkapp.com/developer-inbound-webhook.html"
这里是什么邮戳JSONAPIStrippedTextReply
回复:
"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>'
请注意,在字符串中 URL 之前的动态锚文本。
在 preg_replace()
中使用正则表达式将 URL 替换为锚点。正则表达式 select URL 并将其替换为包含 href
属性中的 URL 的锚标记。
preg_replace("/([\w]+)[\s]+<([^>]+)>/", "<a href=''></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);
如何使用 PHP 将 link 解析或转换为正确的 <a>
link 格式?
"http://developer.postmarkapp.com/developer-inbound-webhook.html"
这里是什么邮戳JSONAPIStrippedTextReply
回复:
"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>'
请注意,在字符串中 URL 之前的动态锚文本。
在 preg_replace()
中使用正则表达式将 URL 替换为锚点。正则表达式 select URL 并将其替换为包含 href
属性中的 URL 的锚标记。
preg_replace("/([\w]+)[\s]+<([^>]+)>/", "<a href=''></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);