我如何编写两个函数,如果它以指定的字符/字符串开头或以指定的字符串结尾,那么它们将接受字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
我如何编写两个函数,如果它以指定的字符/字符串开头或以指定的字符串结尾,那么它们将接受字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
当前回答
为什么不采取以下措施?
//How to check if a string begins with another string
$haystack = "valuehaystack";
$needle = "value";
if (strpos($haystack, $needle) === 0){
echo "Found " . $needle . " at the beginning of " . $haystack . "!";
}
输出:
在valuehaystack的开头找到值!
请记住,如果在干草堆中没有找到针,strpos将返回false,如果且仅当在索引0处找到针时(即开头),strpos将返回0。
以下是结尾:
$haystack = "valuehaystack";
$needle = "haystack";
//If index of the needle plus the length of the needle is the same length as the entire haystack.
if (strpos($haystack, $needle) + strlen($needle) === strlen($haystack)){
echo "Found " . $needle . " at the end of " . $haystack . "!";
}
在这种情况下,不需要函数startsWith()作为
(strpos($stringToSearch, $doesItStartWithThis) === 0)
将准确返回true或false。
奇怪的是,这么简单,所有的野生函数都在这里泛滥。
其他回答
拉里维尔9.0
如果你正在使用Laravel,那么你可以执行以下操作(如果你没有使用Laraver,那么你真的应该这样做)。
Str::of('a long string')->startsWith('a');
Str::of('a long string')->endsWith('string');
//true
//true
我会这样做
function startWith($haystack,$needle){
if(substr($haystack,0, strlen($needle))===$needle)
return true;
}
function endWith($haystack,$needle){
if(substr($haystack, -strlen($needle))===$needle)
return true;
}
这可能奏效
function startsWith($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) == $needle;
}
资料来源:https://stackoverflow.com/a/4419658
简短易懂的一行,没有正则表达式。
startsWith()是直接向前的。
function startsWith($haystack, $needle) {
return (strpos($haystack, $needle) === 0);
}
endsWith()使用稍微花哨且缓慢的strrev():
function endsWith($haystack, $needle) {
return (strpos(strrev($haystack), strrev($needle)) === 0);
}
您可以使用substra_compare函数检查开头和结尾:
function startsWith($haystack, $needle) {
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
这应该是PHP7(基准脚本)上最快的解决方案之一。在8KB的干草堆、各种长度的针以及完全、部分和不匹配的情况下进行测试。strncmp是一种更快的开始方式,但它不能检查结束方式。