Jump to content

How to make preg_match for links in the text?


AndyPSV

Recommended Posts

I've got function that works pretty fine (it replaces http:// & www with links <a href='' etc.), but the problem is that when it finds "www" phrase in the text it also replaces it with link

 

What I want to do is to make it only replace it, when it appear www. <- "dot"; something here & "." <- dot + 1 sign at least.

as an example: 'www.p.pl' would be done as link, but "www", "www.", "www.s", "www..", "www.s." wouldn't be

 

Hope, it's clear; thanks.

 

function rplc($x,$style='') {
/* IF _SERVER[HOST], the same -> NO: target=_blank */
$x = ereg_replace('[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*','<a href=\'mailto:\\0\' '.$style.'>\\0</a>',$x);
$x = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a target='_blank' href='\\0'>\\0</a>",$x);
$x = ereg_replace("(^| |.)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a target='_blank' href=\"http://\\2\">\\2</a>",$x);
return $x;
}

Hi Andy!

 

Run this sample code, I think it does what you want. :)

 

Input: an example: www.p.pl would be done as link, but "www", "www.", "www.s", "www..", "www.s." wouldn\'t

 

Code:

<?php 
$pattern=',(www\.(\w+(?:\.\w+)+)),';
$replacement='<a target=\'_blank\' href="http:\1">\2</a>';
$subject='an example: www.p.pl would be done as link, but "www", "www.", "www.s", "www..", "www.s." wouldn\'t ';
$s=preg_replace($pattern,$replacement,$subject);
echo htmlentities($s).'<br />';
?>

 

Output: an example: <a target='_blank' href="http:www.p.pl">p.pl</a> would be done as link, but "www", "www.", "www.s", "www..", "www.s." wouldn't

 

Is this what you're looking for?

 

 

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.