Jump to content

Regex


Trykiz

Recommended Posts

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 :(

Link to comment
https://forums.phpfreaks.com/topic/259718-regex/
Share on other sites

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.

 

:)

Link to comment
https://forums.phpfreaks.com/topic/259718-regex/#findComment-1331296
Share on other sites

  • 2 weeks later...

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;
?>

Link to comment
https://forums.phpfreaks.com/topic/259718-regex/#findComment-1334864
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.