PHP preg_replace - www or http://

大兔子大兔子 提交于 2019-12-03 18:14:32

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.

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.

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