0

Here's my code:

$post = $_POST['test'];
$pattren='/((([http]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\/+=&#?;%@,.\w_]*)#?(?:[\w]*)?))/';
preg_match_all( $pattren, $post, $matches);

foreach($matches[0] as $match) {
    $images[]= "<a href=\"$match\" target=\"_blank\" >$match</a> ";
}

for ($i = 0, $c = count($images); $i < $c; $i++) {
    $html_links = str_replace($pattren,$images[$i], $post);
}

echo $html_links;

I'm trying to get all urls from $post and convert them to links, but something is wrong.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
majid
  • 3
  • 3

2 Answers2

2

There are many things wrong with this code, including:

Not sure where you've got your regular expression ($pattren) from, but it looks like complete gibberish to me - [http]{3,9}: means "any of the characters 'h', 't', or 'p', repeated between 3 and 9 times, followed by a colon" - so it would match "thppppppt:", which doesn't look much like the beginning of a URL to me.

str_replace has nothing to do with regular expressions, so str_replace($pattren, ... is looking for the text of that regular expression in the input.

In actual fact, I'm not sure what replacement you are expecting to happen in that loop, since you've already copied $match into the correct parts of the string.

You are over-writing the variable $html_links every time around your second loop. There is also no need for 2 loops, unless there is code not shown - you could simply build the string in the foreach loop and do away with the $images array altogether.

And, incidentally, you have spelled "pattern" wrong, and used an inconsistent convention for your curly-braces - some prefer the { on its own line, some on the line with the for/foreach, but you've managed one of each. [Neither of these will affect the code, though]

IMSoP
  • 89,526
  • 13
  • 117
  • 169
0

use preg_replace()

$post = $_POST['test'];
$pattren='%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s';
$html_links = preg_replace($pattren, '<a href="$1" target="_blank">$1</a>', $post);
echo $html_links;

Updated with a good pattern from here.

Community
  • 1
  • 1
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • While this eliminates most of the problem code I mentioned, I'm still not convinced of the usefulness of that regular expression. – IMSoP Aug 18 '12 at 16:45
  • I didn't check the pattern, but modified. Check answer – Mihai Iorga Aug 18 '12 at 16:51
  • Well, it took me a while to figure out why, but yeah, that works. I see there's a newer (and better explained) version here: http://daringfireball.net/2010/07/improved_regex_for_matching_urls – IMSoP Aug 18 '12 at 17:08