获取 PHP 字符串中第一个 Alpha 之前的所有数字
Get all numeric before first Alpha in PHP String
我正在尝试获取 PHP 字符串中 space/alpha 之前的所有数字。
示例:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
如何像上面的例子一样获取字符串的所有数字?
我有个想法先获取 Alpha 的位置,然后获取该位置之前的所有数字。
我已经使用
成功获得职位
preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
但是我还没有完成位置前的数字。
我该怎么做,或者有人知道如何解决我的想法?
任何帮助将不胜感激。
这里有一个在大多数情况下都适用的非常老套的方法:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
这个函数就可以了!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>
您不需要像您展示的示例那样对字符串使用正则表达式,或者根本不需要任何函数。您可以将它们转换为整数。
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number会为您处理。
但是,由于这些规则,还有一些其他类型的字符串无法使用。例如,'-12 Car'
或 '412e2 8all'
.
如果您确实使用了正则表达式,请务必使用 ^
将其锚定到字符串的开头,否则它将匹配字符串中任何位置的数字,就像此处的其他正则表达式答案一样。
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
我正在尝试获取 PHP 字符串中 space/alpha 之前的所有数字。
示例:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
如何像上面的例子一样获取字符串的所有数字?
我有个想法先获取 Alpha 的位置,然后获取该位置之前的所有数字。 我已经使用
成功获得职位preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
但是我还没有完成位置前的数字。
我该怎么做,或者有人知道如何解决我的想法?
任何帮助将不胜感激。
这里有一个在大多数情况下都适用的非常老套的方法:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
这个函数就可以了!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>
您不需要像您展示的示例那样对字符串使用正则表达式,或者根本不需要任何函数。您可以将它们转换为整数。
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number会为您处理。
但是,由于这些规则,还有一些其他类型的字符串无法使用。例如,'-12 Car'
或 '412e2 8all'
.
如果您确实使用了正则表达式,请务必使用 ^
将其锚定到字符串的开头,否则它将匹配字符串中任何位置的数字,就像此处的其他正则表达式答案一样。
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';