检查长度至少为 1 个字符的字符串

发布于 2024-12-19 04:58:47 字数 261 浏览 4 评论 0原文

我经常看到 strlen 使用。这两个测试对于 $str 的所有值都等效吗?

is_string($str) && 0 !== strlen($str)

is_string($str) && '' !== $str

I often see strlen used. Are these 2 tests equivalent for all values of $str?

is_string($str) && 0 !== strlen($str)

is_string($str) && '' !== $str

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

秋叶绚丽 2024-12-26 04:58:47

是的,这两种说法在逻辑上是等价的。我最喜欢的给这只猫剥皮的方法:

is_string($str) && !empty($str)

...虽然 empty('0')true叹息,PHP...),所以这可能更好:

$str !== ''

另请参阅:检查字符串是否为空$str == '' 和 之间有区别吗PHP 中的 strlen($str) == 0?

Yes, those two statements are logically equivalent. My preferred ways to skin this cat:

is_string($str) && !empty($str)

...though empty('0') is true (sigh, PHP...), so this is probably even better:

$str !== ''

See also: Checking if the string is empty and Is there a difference between $str == '' and strlen($str) == 0 in PHP?

安静被遗忘 2024-12-26 04:58:47

它们非常接近,除了 strlen() 将为 NULL 字符串返回 0,因此如果您的 $str > 为 NULL,第一个测试中的 0 !== strlen($str) 表达式的计算结果将为 true,而 '' !== $str 在你的第二个测试中将评估为

They're pretty close, except that strlen() will return 0 for NULL strings, so if your $str was NULL, the 0 !== strlen($str) expression in your first test would evaluate to true, while the '' !== $str in your second test would evaluate to false.

不美如何 2024-12-26 04:58:47

是的,它们是相同的..

我会使用:

is_string($str) && strlen($str) > 0

yes, they are the same..

I would use:

is_string($str) && strlen($str) > 0
秉烛思 2024-12-26 04:58:47

试试这个

strlen($str) > 0

!== 是强类型,可能无法正确匹配 0。

Try this

strlen($str) > 0

!== is a strong type and might not be match the 0 properly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文