PHP preg_replace - www or http: //

Really stuck on something simple. I have a chatbox / shoutbox where arbitrary URLs can be entered. I want to find every single URL (separated by spaces) and wrap it in tags.

Example: =Harry you're a http://google.com wizard!Harry you're a $lhttp://google.com$l wizard!

Example: =Harry you're a http://www.google.com wizard!Harry you're a $lhttp://www.google.com$l wizard!

Example: Harry you're a www.google.com wizard!=Harry you're a $lwww.google.com$l wizard!

Sorry if this is a stupid question; I'm just trying to get something to work, and I'm not a php expert :(

+3
source share
3 answers

There is an interesting article on regular expression URLs . In PHP, it will look like this:

$pattern = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?ยซยป""โ€˜โ€™]))/";

$inp = "Harry you're a http://google.com wizard!";
$text = preg_replace($pattern, "[supertag]$1[/supertag]", $inp);

And, of course, replace [supertag], and [/supertag]the corresponding values.

+13
source

You want to use what is called Regular Expression .

, PHP regexp, , .

, , preg_replace(), , , .

, , , URL- , , :

$text = "derp derp http://www.google.com derp";
$text = preg_replace(
  '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@',
  '[yourtag]$1[/yourtag]',
  $text
);
echo $text;

:

derp derp [yourtag]http://www.google.com[/yourtag] derp

, preg_replace() URL- ( ) $text , .

+1
$text = " Helloooo try thiss http://www.google.com and www.youtube.com :D it works :)";

$text = preg_replace('#http://[a-z0-9._/-]+#i', '<a href="$0">$0</a>', $text);

$regex = "#[ ]+(www.([a-z0-9._-]+))#i";

$text = preg_replace($regex," <a href='http://$1'>$1</a>",$text);

echo $text;
+1
source

All Articles