获取PHP字符串中第一个字母之前的所有数字
我试图在PHP字符串中获取空格/alpha之前的所有数字 示例:获取PHP字符串中第一个字母之前的所有数字,php,regex,string,yii2,numeric,Php,Regex,String,Yii2,Numeric,我试图在PHP字符串中获取空格/alpha之前的所有数字 示例: <?php //string $firstStr = '12 Car'; $secondStr = '412 8all'; $thirdStr = '100Pen'; //result I need firstStr = 12 SecondStr = 412 thirdStr = 100 但我还没做完在定位前得到数字 我该怎么做,或者有人知道如何修正我的想法? 任何帮助都将不胜感激。以下是一种在大多数情况下都能奏效的非
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
但我还没做完在定位前得到数字
我该怎么做,或者有人知道如何修正我的想法?
任何帮助都将不胜感激。以下是一种在大多数情况下都能奏效的非常粗糙的方法:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
以下是一种在大多数情况下都能奏效的非常老练的方法:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
此功能将完成此工作
<?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);
?>
此功能将完成此任务
<?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.
我会帮你处理的
但是,由于这些规则,还有一些其他类型的字符串无法使用。例如,'-12车'
或'412e2 8all'
如果确实使用正则表达式,请确保使用
^
将其锚定到字符串的开头,否则它将与字符串中的任何数字匹配,就像这里的其他正则表达式一样
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
您不需要像前面所示的示例那样对字符串或任何函数使用正则表达式。你可以把它们转换成整数
$number = (int) $firstStr; // etc.
我会帮你处理的
但是,由于这些规则,还有一些其他类型的字符串无法使用。例如,'-12车'
或'412e2 8all'
如果确实使用正则表达式,请确保使用
^
将其锚定到字符串的开头,否则它将与字符串中的任何数字匹配,就像这里的其他正则表达式一样
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
这两种方法都很有效,我想,我会使用你的第一个建议,而不使用正则表达式。非常感谢。我想,这两种方法都很有效,我只使用你的第一个建议,不使用正则表达式。非常感谢你。