我正在查看一些代码并开始思考使用 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/