PDA

View Full Version : Regular Expressions, urls in text


piz
07-26-2003, 01:45 PM
Hi,
I wanted to use the function from the zend code gallery (http://www.zend.com/codex.php?id=395&single=1) to generate urls in a text.

The function works great, but only if the "www." is not just after a line break.
I have no idea about using Regular Expressions, how do i change this to include a possible line break before the "www."? It has to be in the second line i think.
function html_activate_links($str) {
$str = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1" target="_blank">\\1</a>', $str);
$str = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2" target="_blank">\\2</a>', $str);
$str = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href=\"mailto:\\1\">\\1</a>', $str);
return $str;
}

Thx.
Greetz
Paul

MrPink
07-27-2003, 07:40 PM
I use this one:


function addLink($link) {
$link = str_replace("http://","";,$link); //removes 'http://' if present.....
$link = preg_replace("/(?:^|\b)(((www\.))([\w\.]+)([,:%#&\/?=\w+\.-]+))(?:\b|$)/is", "<a href=\"http://$1\" target=\"_blank\">$1</a>", $link);

return $link;
}

$myLink="http://www.mydomain.com";;
// or $myLink="www.mydomain.com";;
// works fine also....
print addLink($myLink);


H.T.H.

ReadMe.txt
07-27-2003, 09:56 PM
if you just stick (?:\n)+ at the end of each search string you should be ok. that just means "match if there is or isn't a preceding newline character of any kind"

i use preg as opposed to ereg so i'm not sure whether or not this will work in single quotes

piz
07-27-2003, 10:35 PM
At the end of each search string?
Ok, I'll try it.

It is not the \n what causes the problem, its the <br>, so I put an > instead there... let's see...

The + stands for leading characters?
Oh God I have to learn Regular Expressions... yet...

mh, it dowsn't work.
Where exactly I have to put the ">" ?

Thx.
Greetz
piz

piz
07-27-2003, 10:44 PM
Yeah I managed it!!
I modified the second line this way:
$str = eregi_replace('([[:space:]?\n?>()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2" target="_blank">\\2</a>', $str);

Only the Mail-Link doesn't work...
But I'll find it out :-)

Thx.

@ReadMe, I wouldn't replace the http://, there are a lot of links without www, what do you do then?

Saludo
piz