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

Link to comment
Share on other sites

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?

 

 

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.