从变量中提取第一个数字

Extract first number(s) from variable

我有总是以一个或多个数字开头的变量,需要脚本来确定这个数字在哪里结束,现在举个例子,变量可以如下所示:

1234-hello1.jpg

1 hello1.gif

1234hello1.gif

123456 hello1.gif

我想说的是 explode 函数不起作用,而且我的正则表达式很差,我只需要保留第一个数字并忽略字符串中的任何其他数字。我只需要留下粗体数字即可。

提前致谢...

我想你可以用下面的代码从你的 sting 中删除 no。

preg_replace('/[0-9]+/', '', $string);

这里 $string 是变量,您可以根据您的变量名称更改此名称。

RegEx 确实是可行的方法:

function getVal($var){
    $retVal = '';

    if(preg_match('#^(\d+)#', $var, $aCapture)){  //Look for the digits
        $retVal = $aCapture[1];    //Use the digits captured in the brackets from the RegEx match
    }
    return $retVal;
}

这样做的目的是只查找字符串开头的数字,将它们捕获到一个数组中,然后使用我们想要的部分。

preg_match('/^[0-9]+/', $yourString, $match);

现在您可以检查 $match 的整数。

$arr = str_split($str);
for($i = 0; $i < count($arr); ++$i){
   if(!is_numeric($arr[$i])){
       echo "Number ends at index: " . $i;
       break;
   }
}

如果您愿意,也可以使用 $arr[$i] 将数字放入数组中。 这可能比使用正则表达式更具可读性。

您可以添加允许一位小数点的逻辑,但从问题来看您似乎只需要整数。

http://sandbox.onlinephpfunctions.com/code/fd21437e8c1502b56572a624cf6e4683cf483a8d - 工作代码示例

如果你确定数字是一个整数,在开头并且一直存在,你可以使用sscanf:

echo sscanf($val, '%d')[0];

这是您需要的正则表达式:

^.*\b([0-9]+)

我不知道你写的是哪种语言,所以只给你正则表达式。它已在 Notepad++ 中使用您的示例进行测试。

彼得·贝内特, 你可以这样试试。首先,将字符串(1234-hello1.jpg) 转换为数组。 然后你可以检查给定的数组元素是否为数字。

$str = "1234-hello1.jpg";       //given string
$count = strlen($str);          //count length of string
$num = array();

for($i=0; $i < $count; $i++)
{
    if(is_numeric($str[$i]))     //to check element is Number or Not
    {
        $num[] = $str[$i];       //if it's number, than add it to another array
    }
    else break;                  //if array element is not a number. exit **For** loop
}

$number = $num;                //See o/p
$number = implode("", $number);   
echo $number;                    // Now $number is String.

输出

 $num = Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
);


$number = "1234";   //string

所以你终于得到了你需要的字符串。

这是完整的工作脚本,感谢@user1...

$str = "1234-hello1.jpg";
$arr = str_split($str);
for($i = 0; $i < count($arr); ++$i){
   if(!is_numeric($arr[$i])){
       //echo "Number ends at index: " . $i;       
       break;
  } else {
        $num[] = $str[$i];   
   }
}

$fullNumber = join("", $num);

echo $fullNumber;