PHP preg_replace - www or http://

2020-06-27 18:46发布

Really stuck on what seems to be something simple. I have a chatbox/shoutbox where there may be arbitrary URLs entered. I want to find each individual 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 daft question; I'm just trying to make something work and I'm no php expert :(

3条回答
家丑人穷心不美
2楼-- · 2020-06-27 19:08

You'll want to use what's called a Regular Expression.

You should write a regular expression, and then use one of PHP's various regexp functions to do what you want.

In this case, you should probably use the preg_replace() function, which finds a string that matches your regular expression and replaces it as you specify.

The regular expression you are looking for is particularly tricky to write, as URLs can come in many forms, but I found an expression which should do the trick:

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

This will output:

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

You can see that the preg_replace() function found the URL (and it will find multiple) in $text, and put the tags I specified around it.

查看更多
倾城 Initia
3楼-- · 2020-06-27 19:09
$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;
查看更多
可以哭但决不认输i
4楼-- · 2020-06-27 19:10

There is an interesting article about a URL regular expression. In PHP this would look like:

$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] with the appropriate values.

查看更多
登录 后发表回答