繁体   English   中英

preg_replace无法正常工作

[英]preg_replace isn't working as expected

我编写了一个简单的函数,该函数接受一段文本,从中提取网址,然后用<a href>标记替换所有网址。

例如, http://site.com应该成为<a href="http://site.com">http://site.com</a>

码:

function parseUrls( $string )
{
    $string = trim($string);
    $pattern = '%\bhttp[s]?://[A-z0-9/\.\-_]+%i';
    $replacement = '<a href="$1">$1</a>';

    $string = preg_replace($pattern, $replacement, $string);

    return $string;
}

但是,如果我将以下字符串作为输入传递:

你好https://google.com测试http://test.com/something.html abc http://site.com

我得到的输出是:

hello <a href=""></a> test <a href=""></a> abc <a href=""></a> 

也就是说,URL被匹配,但是$replacement没有正确应用。 可能我的$1用法有误吗?

我究竟做错了什么?

表达式中没有定义捕获组 (通常由()完成)。 因此$1是空的。 但是$0在您的替换模式中保留了完全匹配的字符串。

所以无论使用

$replacement = '<a href="$0" target="_BLANK">$0</a>';

要么

$pattern = '%\b(http[s]?://[A-z0-9/\.\-_]+)%i';
//             ^                          ^
//             |                          |
//             +-----  Capture group -----+

您没有$1会引用的捕获组。

使用$replacement = '<a href="$0" target="_BLANK">$0</a>'; 代替。

另外,请不要在字符类中使用Az (它比您想象的要匹配得多:ASCII Za之间有一些非字母字符)。 AZ就足够了,因为无论如何您都不区分大小写。

您需要使用方括号将表达式分组才能使用$ 1。

$ pattern ='%\\ b(http [s]?:// [A-z0-9 /.-_] +)%i';;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM