Reputation:
In PHP, I want to make it so that if a user types:
[LINK] url [/LINK]
It will replace it with the anchor tag:
<a href=url>url</a>
How would I show this? I'm not sure how to translate this into regex...
I've tried the following:
[LINK][a-zA-Z0-9_-.]+[/LINK]
But obviously that isn't right :(
Upvotes: 0
Views: 462
Reputation: 46660
Catch links but would always require leading http:// or https:// else the url would be example.com/google.com also you should use preg_replace_callback() as its possible to xss unsanitized input.
Here are some examples:
<?php
//The callback function to pass matches as to protect from xss.
function xss_protect($value){
if(isset($value[2])){
return '<a rel="nofollow" href="'.htmlentities($value[1]).'">'.htmlentities($value[2]).'</a>';
}else{
return '<a rel="nofollow" href="'.htmlentities($value[1]).'">'.htmlentities($value[1]).'</a>';
}
}
$link ='[LINK]http://google.com[/LINK]';
$link = preg_replace_callback("/\[LINK\](.*)\[\/LINK\]/Usi", "xss_protect", $link);
echo $link;
?>
<a rel="nofollow" href="http://google.com">google.com</a>
Or Strip the http:// & https:// from the link then append it when outputting.
<?php
$link ='[LINK]google.com[/LINK]';
$link = preg_replace_callback("/\[LINK\](.*)\[\/LINK\]/Usi", "xss_protect", str_replace(array('http://','https://'),'',$link));
echo $link;
?>
<a rel="nofollow" href="http://google.com">google.com</a>
Or A different way to have BB code links, then you can specify Link name from link address, the call back function can be made to handle multiple types of outputs.
<?php
$link ='[LINK=google.com]Google[/LINK]';
$link = preg_replace("/\[LINK=(.*)\](.*)\[\/LINK\]/Usi", "xss_protect", str_replace(array('http://','https://'),'',$link));
echo $link;
?>
<a rel="nofollow" href="http://google.com">Google</a>
Upvotes: 0
Reputation: 16462
$str = '[LINK]http://google.com[/LINK]';
$str = preg_replace('/\[link\]([^\[\]]+)\[\/link\]/i', '<a href="$1">$1</a>', $str);
echo $str; // <a href="http://google.com">http://google.com</a>
Explanation:
\[link\] Match "[LINK]"
([^\[\]]+) Match any character except "[" and "]"
\[\/link\] Match "[/LINK]"
i Make it case-insensitive
Upvotes: 1