PHP 问答之 如何使用startsWith()和endsWith()函数
实战问题
如果它以指定的字符/字符串开头或以它结尾,我如何编写两个函数来接受一个字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
解决方案
function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
如果您不想使用正则表达式,请使用此选项。
加入我们共同交流
群名称:PHP源码大全
QQ群号:907415141