在 PHP 中实现 String 的 StartsWith 和 EndsWith
http://www.tuicool.com/articles/ZJ7f2in
在 PHP 中实现 String 的 StartsWith 和 EndsWith
时间 2015-08-01 06:37:06 Leona+
原文 http://leonax.net/p/7804/string-startswith-and-endswith-in-php/
主题 PHP
和 Javascript 一样,PHP 中也没有对 String 实现 StartsWith 和 EndsWith 这两个方法。由于这两个方法很常用,我们只好自己来实现一下。
在 PHP 4 中,常见的做法和 Javascript 类似,如下:
if ( ! ( function_exists ( 'str_starts_with' ) ) {
function str_starts_with ( $haystack , $needle ) {
return substr ( $haystack , 0 , strlen ( $needle ) ) === $haystack ;
}
}
if ( ! ( function_exists ( 'str_ends_with' ) ) {
function str_ends_with ( $haystack , $needle ) {
return substr ( $haystack , - strlen ( $needle ) ) === $haystack ;
}
}
上面的方法会使用更多的内存,并且对字符串扫描了两遍,效率不高。这种方法在 PHP 5 中已经过时了,因为 PHP 5 给出了一个 substr_compare 方法,可以直接比较子字符串,如果代码就可以简化成这样:
if ( ! ( function_exists ( 'str_starts_with' ) ) {
function str_starts_with ( $haystack , $needle ) {
return substr_compare ( $haystack , $needle , 0 , strlen ( $needle ) ) === 0 ;
}
}
if ( ! ( function_exists ( 'str_ends_with' ) ) {
function str_ends_with ( $haystack , $needle ) {
return substr_compare ( $haystack , $needle , - strlen ( $needle ) ) === 0 ;
}
}
上述实现的效率至少快了一倍。由于历史遗留的问题,很多现存代码都没有更新,比如 WordPress 的源码中就存在了 老版本的实现 。如果你已经在使用 PHP 5 或者 HHVM,不妨试试第二种实现。

浙公网安备 33010602011771号