Jump to content

preg_replace problems - trying to convert parts of submitted text to URLs


Flipperbw

Recommended Posts

The Issue

 

My users can post comments. I want to turn the hidden links within those comments into clickable URLs. I have the following function to do this:

 

if (!function_exists('create_link'))
{
  function create_link($url) {

$pattern = "#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie";

$link_title = character_limiter(preg_replace($pattern, "$3", $url), 50);
    
$link = preg_replace($pattern, "'<a href=\"$1\" target=\"_blank\">{LINK_TITLE}</a>$4'", $url);
    if ($link == $url)
    {
      $url = 'http://' . $url;
      $link = preg_replace($pattern, "'<a href=\"$1\" target=\"_blank\">{LINK_TITLE}</a>$4'", $url);
    }
    
    if ($link != $url)
    {
      $result = str_replace('{LINK_TITLE}', $link_title, $link);
    }
    else
    {
      $result = FALSE;
    }
    return $result;
  }
}

 

 

I know that the regex is pretty bad. It kind of works, but makes every single thing with a period into a link, and messes up sometimes with target= portion where it will actually display that.

 

I've tried a bunch of other regex's but every single one gives me problems, typically like "php unknown modifier ]" or ")" or something.

 

here's how I call this function when users hit submit in the comment field:

 

$words = preg_split("/[\s,]+/", $comment);
    foreach ($words as $word) {
      if ($link = create_link($word))
      {
        $comment = str_replace($word, $link, $comment);

 

 

I just want to convert the right links into links. is something like:

 

^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$

 

any better? I don't know, nothing seems to work.

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.