简体   繁体   中英

How can I say in php that a variable can only be numbers or text?

I have a variable in PHP as in below:

        $currentMakeText = $advert->getMakeText();
        if ($currentMakeText == '' || $currentMakeText === null || $currentMakeText == '0') {

In the if statement I want to check if it is only text and if it is only numbers.

To check for both:

if(ctype_alnum($currentMakeText)) { }

Or to check for either:

if(ctype_alpha($currentMakeText)) {
    //letters
} elseif(ctype_digit($currentMakeText)) {
    //digit
}

您可以尝试以下一种方法:

if(is_string($currentMakeText) || is_numeric($currentMakeText))

Just use preg_match with a regex of [a-zA-Z0-9 ] like this:

$currentMakeText = $advert->getMakeText();

if (preg_match('/[a-zA-Z0-9 ]/', $currentMakeText)) {
  // Your code here.
}

Note I added a space after a-zA-Z0-9 so it can detect sentences of combinations of words that have spaces. But you could just remove that space to purely check for alpha number characters like this [a-zA-Z0-9] .

And you could simplify it more by using the i option on the preg_match for case insensitivity:

$currentMakeText = $advert->getMakeText();

if (preg_match('/[a-z0-9 ]/i', $currentMakeText)) {
  // Your code here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM