Jump to content

[SOLVED] preg_replace URLS


karldesign

Recommended Posts

I have the following funtion:

function parseUrl($str_haystack)
{
$str_haystack = str_replace('http://', '', $str_haystack);
$str_needle = preg_replace("/(www.)([^\s,]*)/i", "<a href='http://$1$2' target='_blank' class='ld'>$1$2</a>", $str_haystack);
return $str_needle;
}

 

I am parsing URLs from a string, which works fine until I have a URL as such: www.domain.com/subdomain.php?id=234...

 

Any ideas why? Not familiar with preg_replace in honesty...

Link to comment
Share on other sites

No, the '...' was just me typing.

 

function nl2p($str)
{
$new_str = preg_replace('/<br \\/>\s*<br \\/>/', "</p><p>", nl2br($str));
return '<p>' . $new_str . '</p>';
}

 

This is the function I perform before the parseUrl function (above). So when I have www.domain.com its fine. But if I have www.domain.com/subdomain.php?id=1234 the page it links to is www.domain.com/subdomain.php?id=1234</p><p> . Now I took out the </p><p> from the nl2p function and it worked, but the formatting of the text went to pot...

Link to comment
Share on other sites

Found a solution... not too sure if its the best way or the right way, but its working...

 

I added a ' ' (whitespace) before each <p> and </p>. This seemed to end the regex...

 

Hope this is useful to anyone else too!

 

Feel free to use it.

Link to comment
Share on other sites

Ok, I have found a way of allowing all URLs, https: and http...

So if you are interested, here it is.

 

function parseUrl($str_haystack)
{
$str_haystack = str_replace('http://', '', $str_haystack);
$str_haystack = str_replace('www.', 'http://www.', $str_haystack);
$str_needle = preg_replace("/(http:\/\/|https:\/\/)([^\s,]*)/i","<a href='$1$2' target='_blank' class='ld'>$2</a>",$str_haystack);
return $str_needle;
}

 

Please notice how the output doesn't show $1, this is because I didn't want to show http: or https: in the output link... I expect you could add ftp: and any others to the | (or) list... I would however suggest testing it fully before using it, as I haven't done any testing.

 

Hope this helps!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.