php: Remove URL from string
php, regex, string
Solution
If you want to remove everything, link and after the link, like via thing in your example, the below may help you:
$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?).*$)@";
echo preg_replace($regex, ' ', $string);
If you want to keep them:
$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
echo preg_replace($regex, ' ', $string);
Problem
I have many strings (twitter tweets) from which I would like to remove the links when I echo them . I have no control over the string and even though all the links start with http, they can end with a "/" or a ";" not, and be followed or not by a space. Also, sometimes there is not space between the link and the word just before it. One example of such string: ``` The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge ``` I have try to play around with preg_replace, but couldn't come up with a solution that fit all the exceptions: ``` <?php echo preg_replace("/\http[^)]+\;/","",$feed->itemTitle); ?> ``` Any idea how I should proceed? Edit: I have tried ``` <?php echo preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', ' ', $feed->itemTitle); ?> ``` but still no success. Edit 2: I found this one: ``` <?php echo preg_replace('^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$^',' ', $feed->itemTitle); ?> ``` which remove the link as expected but it also deletes the entire string when there is not space between the link and the word that precedes it.