我有字符串:
$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
如何找到这些字符串中的数字?
也许有功能:
function numbers($string){
// ???
$first = ?;
$second = ?;
}
例如:
function numbers($one){
// ???
$first = 4;
$second = 5;
}
function numbers($two){
// ???
$first = 2;
$second = NULL;
}
最好的方法可能是正则表达式,但我如何在我的示例中使用它?也许没有正则表达式?
您可以使用常用表达 http://php.net/book.pcre为了这。这\d
转义序列 http://php.net/regexp.reference.escape将匹配主题字符串中的所有数字。
例如:
<?php
function get_numerics ($str) {
preg_match_all('/\d+/', $str, $matches);
return $matches[0];
}
$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));
https://3v4l.org/DiDBL https://3v4l.org/DiDBL
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)