PHP preg_replace - www or http://

不想你离开。 提交于 2019-12-05 03:38:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!