确定变量是否有任何文本

发布于 2024-10-04 02:02:10 字数 264 浏览 0 评论 0原文

我想确定变量是否有任何文本。
例如,我当前的代码是这样的:

if (is_numeric ($id)) 
{
  //do stuff
} 
else 
{
  // do other stuff 
}

但是,如果我的变量同时包含字符串和数字,则会出现问题
例如“你已经93岁了”,
因为它发现数字 93 存在并认为变量是数字。
我希望 if 语句仅在变量中完全没有文本的情况下“执行操作”。

谢谢

I would like to determine whether or not a variable has any text at all.
For instance, my current code is this:

if (is_numeric ($id)) 
{
  //do stuff
} 
else 
{
  // do other stuff 
}

However, there is a problem if my variable contains both a string and a number
such as "you are 93 years old",
because it sees that number 93 is present and considers the variable numeric.
I want the if statement to only "do stuff" if there is absolutely no text in the variable at all.

Thanks

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

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

发布评论

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

评论(2

疯狂的代价 2024-10-11 02:02:10

尝试将值转换为 int (或 float),然后将其与未更改的版本进行比较。它们应该匹配值(但不匹配类型),

if((int)$id == $id) {
} else {
}

另一个选择是使用 preg_match("/^([\d.\-]+)$/", $id)。这将使您能够非常具体地了解让 $id 包含哪些字符。然而,使用正则表达式应被视为最终选择(出于性能原因)

Try casting the value to int (or float) then compare it back to the unaltered version. They should match values (but not type)

if((int)$id == $id) {
} else {
}

another option would be to use preg_match("/^([\d.\-]+)$/", $id). This would allow you to be very specific about what characters you let $id contain. However using regexp should be considered as the final choice (for performance reasons)

染火枫林 2024-10-11 02:02:10
if(empty($var) && $var !== "0" && $var !== 0) {
    // it's really empty, not a string "0" and not a numeric 0
}

为了完整起见,您还可以检查它是否不是布尔值 false

if(empty($var) && $var !== "0" && $var !== 0) {
    // it's really empty, not a string "0" and not a numeric 0
}

You could also check if it's not a boolean false for the sake of completeness.

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