Trykiz Posted March 26, 2012 Share Posted March 26, 2012 Hi, I need help with regex. I need to replace all urls (http://example.com) with <a href='http://example.com'>http://example.com</a> this, but if In text already exist <a href='http://example.com'>http://example.com</a> do nothing with it. Example text: Maecenas ornare viverra rhoncus http://google.com . Donec pulvinar ipsum nec felis mollis non iaculis turpis pellentesque <a href='http://example.com'>http://example.com</a> . Pellentesque vel convallis lacus <a href='http://www.phpfreaks.com'>phpfreaks</a> . preg_replace('/(http:\/\/[a-zA-Z0-9.\/=@]+)/', '<a href=\\1>\\1</a>', $param); But it's replacing <a href='http://www.phpfreaks.com'>phpfreaks</a> to <a href='<a href='http://www.phpfreaks.com'>http://www.phpfreaks.com</a>'>phpfreaks</a> Thanks! Sorry for wrong categorie Quote Link to comment Share on other sites More sharing options...
ragax Posted March 26, 2012 Share Posted March 26, 2012 Hi Trykiz, Welcome to the phpfreaks forum! Here's one way to deal with it. Code: <?php $string='Maecenas ornare viverra rhoncus http://google.com . Donec pulvinar ipsum nec felis mollis non iaculis turpis pellentesque <a href=\'http://example.com\'>http://example.com</a> . Pellentesque vel convallis lacus <a href=\'http://www.phpfreaks.com\'>phpfreaks</a>'; $regex=',(http://[\w./=@?]++)(?![\'"<]),'; echo htmlentities(preg_replace($regex,'<a href="\\1">\\1</a>',$string)).'<br />'; ?> Output: Maecenas ornare viverra rhoncus <a href="http://google.com">http://google.com</a> . Donec pulvinar ipsum nec felis mollis non iaculis turpis pellentesque <a href='http://example.com'>http://example.com</a> . Pellentesque vel convallis lacus <a href='http://www.phpfreaks.com'>phpfreaks</a> After matching the url, the regex just checks (negative lookahead) that it is not followed by a quote or a < character. Here's more about regex lookarounds. Let me know if you have any questions. Quote Link to comment Share on other sites More sharing options...
.josh Posted March 26, 2012 Share Posted March 26, 2012 this question has been asked a lot of times, please try searching the regex forum. Quote Link to comment Share on other sites More sharing options...
chriscloyd Posted April 6, 2012 Share Posted April 6, 2012 try this <?php function getName($url) { $input = trim($url, '/'); $urlParts = parse_url($input); $domain = preg_replace('/^www\./', '', $urlParts['host']); $parts = explode('.', $domain); return $parts[0]; } $d = 'http://www.google.com'; $tld = getName($d); echo $tld; ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.