从变量中提取第一个数字


Extract first number(s) from variable

我有一些变量总是以一个或多个数字开头,需要脚本来确定这个数字的结束位置,例如,变量可以如下所示:

1234-hello1.jpg

1hello1.gif

1234hello1.gif

12346hello1.gif

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

提前感谢。。。

$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]将数字放入一个数组中。这可能比使用regex可读性高得多。

你可以添加逻辑来允许一个小数点,但从这个问题来看,你似乎只想要整数。

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

如果您确定数字是一个整数,在开头并且始终存在,则可以使用sscanf:

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

Peter Bennett,你可以这样试试。首先,将字符串(1234-hello1.jpg(转换为数组。然后您可以检查给定的数组元素是否为Number。

$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

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

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

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

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;
}

这样做的目的是只查找字符串开头的数字,在数组中捕获它们,并使用我们想要的片段。

这就是您需要的RegEx:

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

我不知道你在写哪种语言,给你RegEx就行了。它在Notepad++中与您的示例一起进行了测试。

这是完整的工作脚本,感谢@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;

我认为您可以使用下面的代码从sting中删除no。

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

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