可能重复:
Need a good regex to convert URLs to links but leave existing links alone
这是我的样本输入:
http://www.website.com/1/
Click here http://www.website.com/2/ or visit the website: http://www.website.com/3/
or http://www.website.com/4/
http://www.website.com/5/
我想要一个PHP函数,将文本中的URL转换为标记,如下所示:
<a href="http://www.website.com/1/">http://www.website.com/1/</a>
Click <a href="http://www.website.com/2/">here</a> or visit the website: <a href="http://www.website.com/3/">http://www.website.com/3/</a>
or <a href="http://www.website.com/4/">http://www.website.com/4/</a>
<a href="http://www.website.com/5/">http://www.website.com/5/</a>
第2行有一个问题:如果网址前面有单词here
,那么该单词应该用作锚文本。我需要在PHP中执行此操作。我认为带有/e
开关的preg_replace可能会帮助我完成这项任务,但我不确定。这是我到目前为止使用的(借用)正则表达式:
preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
// ^---- I've tried adding "|here "
// But I cannot get the order of \\1 and \\2 right
请建议。
答案 0 :(得分:1)
“但是我无法得到\ 1和\ 2的顺序”
捕获组的数量按左括号的顺序排列,因此第一个左括号将始终为$1
。如果您不想这样,请使用named groups。
对于您的问题,您可以尝试此正则表达式
(?:(here)\s*|\b)(\w+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)
$1
中的“here”和$2
中的链接。如果未找到“此处”,则$1
为空。
那么,你需要替换依赖于$1
的内容。如果为空,则用
<a href="$2">$2</a>
否则
<a href="$2">$1</a>
我认为应该可以使用preg_replace_callback
答案 1 :(得分:-1)
我找到了this。
这听起来很有意思,以为我自己没有测试过,我现在正在做它。
课程是这样的:
class MakeItLink {
protected function _link_www( $matches ) {
$url = $matches[2];
$url = MakeItLink::cleanURL( $url );
if( empty( $url ) ) {
return $matches[0];
}
return "{$matches[1]}<a href='{$url}'>{$url}</a>";
}
public function cleanURL( $url ) {
if( $url == '' ) {
return $url;
}
$url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
$url = str_replace( array( "%0d", "%0a" ), '', $url );
$url = str_replace( ";//", "://", $url );
/* If the URL doesn't appear to contain a scheme, we
* presume it needs http:// appended (unless a relative
* link starting with / or a php file).
*/
if(
strpos( $url, ":" ) === false
&& substr( $url, 0, 1 ) != "/"
&& !preg_match( "|^[a-z0-9-]+?.php|i", $url )
) {
$url = "http://{$url}";
}
// Replace ampersans and single quotes
$url = preg_replace( "|&([^#])(?![a-z]{2,8};)|", "&$1", $url );
$url = str_replace( "'", "'", $url );
return $url;
}
public function transform( $text ) {
$text = " {$text}";
$text = preg_replace_callback(
'#(?])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is',
array( 'MakeItLink', '_link_www' ),
$text
);
$text = preg_replace( '#(<a>]+?>|>))<a>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $text );
$text = trim( $text );
return $text;
}
}
它非常易于使用,只需加载您要搜索的文本即可 链接并调用转换方法:
$ text = MakeItLink :: transform($ text);
所有这些代码都来自WordPress,后者已获得许可 GPL