【发布时间】:2021-06-05 05:16:32
【问题描述】:
有没有比检查最后一个字符是“s”还是“z”更勇敢的方法:
if (substr($var, -1, 1) == "s" OR substr($var, -1, 1) == "z") ...
类似
if (substr($var, -1, 1) == "s" OR "z") ...
会很好,但是 PHP 中有这样的东西吗?
【问题讨论】:
有没有比检查最后一个字符是“s”还是“z”更勇敢的方法:
if (substr($var, -1, 1) == "s" OR substr($var, -1, 1) == "z") ...
类似
if (substr($var, -1, 1) == "s" OR "z") ...
会很好,但是 PHP 中有这样的东西吗?
【问题讨论】:
使用in_array 并查找数组中的最后一个字符:
if (in_array(substr($var, -1, 1), ['s', 'z']))
【讨论】:
或许:
in_array(array_pop(explode('', $var)), ['s', 'z'])` ?
可读性并不高,也不英勇,但我知道什么? :)
【讨论】:
厌倦了太容易理解的代码?正则表达式的救援:
preg_match('/[sz]$/', $var)
【讨论】:
[] 是“one of”,$ 是“end of string”,如果你不会,我不推荐。
如果你能够使用 PHP8,那么你应该在 PHP8 中提供这个简单的解决方案。
https://www.php.net/manual/en/function.str-ends-with.php
<?php
$text = 'foods';
if (str_ends_with($text, 's') || str_ends_with($text, 'z')) { ... }
【讨论】: