Reputation: 3442
how do i parse or convert the link to proper <a>
link format with PHP?
"http://developer.postmarkapp.com/developer-inbound-webhook.html"
Here what postmark JSON API StrippedTextReply
response:
"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)
Expecting result:
'This is example body with <a href="http://developer.postmarkapp.com/developer-process-parse.html">link</a>'
Note that text of anchor in dynamic that is before URL in string.
Upvotes: 1
Views: 1864
Reputation: 21489
Use regex in preg_replace()
to replace URL with anchor. The regex select URL and replace it with anchor tag contain that URL in href
attribute.
preg_replace("/([\w]+)[\s]+<([^>]+)>/", "<a href='$2'>$1</a>", $str);
Edit:
If position of text of anchor in string is unknown (before or after of URL), you need to use preg_replace_callback()
to check value of matched group.
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);
Upvotes: 2