PHP 从字符串中提取数字 [英] PHP Extract numbers from a string
问题描述
我想从 PHP 中的字符串中提取数字,如下所示:
如果 string = 'make1to6' 我想提取整个字符串中 'to' 子字符串前后的数字字符.即要提取1和6
if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
我将使用这些返回值进行一些计算.'我想提取整个字符串中to"子字符串前后的数字字符.即要提取 1 和 6
i will be using these returned values for some calculations.' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
字符串的长度不固定,最大长度为10个字符.字符串中'to'两边的数字最多为两位.
The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.
一些示例字符串值:
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
想到类似的东西:
function beforeTo(string) {
return numeric_value_before_'to'_in_the_string;
}
function afterTo(string) {
return numeric_value_after_'to'_in_the_string;
}
我将使用这些返回值进行一些计算.
i will be using these returned values for some calculations.
推荐答案
您可以使用正则表达式,它应该与您的规范完全匹配:
You can use a regular expression as such, it should match exactly your specification:
$string = 'make6to12';
preg_match('{^.*?(?P<before>\d{1,2})to(?P<after>\d{1,2})}m', $string, $match);
echo $match['before'].', '.$match['after']; // 6, 12
这篇关于PHP 从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!