PHP中的startsWith()和endsWith()函数

新手上路,请多包涵

如果它以指定的字符/字符串开头或以指定的字符/字符串结尾,我如何编写两个接受字符串并返回的函数?

例如:

 $str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true

原文由 Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
2 个回答

PHP 8.0 及更高版本

从 PHP 8.0 开始,您可以使用

str_starts_with 手册

str_ends_with 手动

例子

echo str_starts_with($str, '|');

8.0 之前的 PHP

 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;
}

原文由 MrHus 发布,翻译遵循 CC BY-SA 4.0 许可协议

拉拉维尔 9.0

如果您使用的是 Laravel,那么您可以执行以下操作(如果您不使用 Laravel,您真的应该这样做)。

 Str::of('a long string')->startsWith('a');
Str::of('a long string')->endsWith('string');

//true
//true

原文由 Toby Allen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题