PHP字符串是否以另一个字符串结尾的最有效测试是什么? [英] What's the most efficient test of whether a PHP string ends with another string?

查看:443
本文介绍了PHP字符串是否以另一个字符串结尾的最有效测试是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试字符串$str是否以子字符串$test结尾的标准PHP方法是:

The standard PHP way to test whether a string $str ends with a substring $test is:

$endsWith = substr( $str, -strlen( $test ) ) == $test

这是最快的方法吗?

推荐答案

阿萨夫所说的正确. PHP中有一个内置函数可以完全做到这一点.

What Assaf said is correct. There is a built in function in PHP to do exactly that.

substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;

如果$test长于$str,PHP将发出警告,因此您需要首先进行检查.

If $test is longer than $str PHP will give a warning, so you need to check for that first.

function endswith($string, $test) {
    $strlen = strlen($string);
    $testlen = strlen($test);
    if ($testlen > $strlen) return false;
    return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}

这篇关于PHP字符串是否以另一个字符串结尾的最有效测试是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆