如何区分字符串和整数

use*_*339 1 php

今天我遇到了这个问题,如何拆分/区分是str和来自随机输入的int?例如,我的用户可以输入如下: -

  1. A1> str:A,int:1
  2. AB1> str:AB,int:1
  3. ABC> str:ABC,int:1
  4. A12> str:A,int:12
  5. A123> str:A,int:123

我当前的脚本使用substr(输入,0,1)来获取str和substr(输入,-1)来获取int,但是如果输入了案例2,3,4,5或任何其他样式,它将给出错误用户输入

谢谢

Mar*_*ker 8

list($string, $integer) = sscanf($initialString, '%[A-Z]%d');
Run Code Online (Sandbox Code Playgroud)


ker*_*ero 5

使用如下的正则表达式.

// $input contains the input
if (preg_match("/^([a-zA-Z]+)?([0-9]+)?$/", $input, $hits))
{
    // $input had the pattern we were looking for
    // $hits[1] is the letters
    // $hits[2] holds the numbers
}
Run Code Online (Sandbox Code Playgroud)

表达式将查找以下内容

^               start of line
([a-zA-Z]+)?    any letter upper or lowercase
([0-9]+)?       any number
$               end of line
Run Code Online (Sandbox Code Playgroud)

(..+)?在这+意味着"一个或多个"的?手段0 or 1 times.所以你正在寻找任何长期出现或不出现的东西