问题
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 :(
回答1:
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.
回答2:
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.
回答3:
$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;
来源:https://stackoverflow.com/questions/6165552/php-preg-replace-www-or-http