php - 使用 preg_replace 截断字符串的最有效方法?

标签 php regex string performance

我正在查看一些代码并开始思考使用 preg_replace 截断字符串(在本例中为 URI)的最有效方法。

首先 - 我意识到首先使用 preg_replace 对于这个任务来说可能有点矫枉过正,它可能不必要地昂贵,并且最好使用 PHP 的字符串友好函数来处理它,例如作为 substr。我确实知道这一点。

也就是说,考虑这两个不同的正则表达式:

$uri = '/one/cool/uri';    // Desired result '/one/cool'

// Using a back-reference
$parent = preg_replace('#(.*)/.*#', "$1", $uri);

// Using character class negation
$parent = preg_replace('#/[^/]+$#', '', $uri);

默认情况下,我假设在前一种情况下,创建反向引用比不创建反向引用代价更高,因此第二个示例更可取。但是后来我开始怀疑在第二个示例中使用 [^/] 是否比在第一个示例中使用相应的 . 更昂贵,如果是这样,会贵多少?

从可读性的角度来看,我更喜欢第一个示例,并且由于我们正在 split 头发,所以我倾向于在两者之间进行选择(毕竟,编写可读代码也很有值(value))。不过可能只是我个人的喜好。

想法?

最佳答案

我还会测量两个选项的运行时间。文档中的这些信息也可能有帮助:

http://www.php.net/manual/en/regexp.reference.performance.php

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

因此,$parent = preg_replace('#^(.*)/.*#s', "$1", $uri); 可能会加快第一个选项的速度。第二个不需要此设置:

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

关于php - 使用 preg_replace 截断字符串的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654452/

相关文章:

javascript - 用点替换逗号,用逗号替换点

string - 如何在go中有效地连接字符串

php - 是否可以为日期制作一个内容可编辑的表格单元格?

php - 从视频中提取特定帧的最快方法(PHP/ffmpeg/任何东西)

php - 用于获取最近 30 天的每日数据的 MYSQL 查询计数,即使任何日期的数据都不存在

mysql - 如何在 MySQL 中表示交叉应用和拆分字符串

ios - 验证只能包含字母、数字和下划线字符的字符串

php - Telegram 上的内联键盘用于发送到 channel

正则表达式选择除特定 URL 之外的文本正文中的所有 URL(Sublime Text)

regex - 我们可以将值的正则表达式放入 DTD 中吗?