Reputation: 28188
I'm aware there are other answers to similar questions, however I have tried code examples I previously found and cannot get any of them to work.
I want to locate whether a string contains a url (starting with http
or https
) and then convert that link into an actual HTML link by adding <a>
tags around it.
This is the code I have:
$text = 'Yummy brunch http://t.co/5AlmSPZeRd';
if ((strpos($text,'http') !== false)) {
echo "yep!";
preg_replace('!(http|https)(s)?:\/\/[a-zA-Z0-9.?%=&_/]+!', "<a href=\"\\0\">\\0</a>", $text);
}
While my "yep!" message does show (proving that the if
statement is correct), the preg_replace
doesn't occur. What am I doing wrong?
Upvotes: 0
Views: 34
Reputation: 91518
How about:
$text = 'Yummy brunch http://t.co/5AlmSPZeRd';
if ((strpos($text,'http') !== false)) {
echo "yep!";
$text = preg_replace('!https?://\S+!', "<a href=\"$0\">$0</a>", $text);
}
Upvotes: 2