Reputation: 3
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.
Upvotes: 0
Views: 114
Reputation: 39724
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.
Upvotes: 0
Reputation: 98015
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]
Upvotes: 2