我将编写一个PHP函数,从类似以下字符串中提取数字ID:
显而易见的结果是数组([0]=>123 [1]=>1256 [2]=>2) 所以我写了另一个正则表达式来消除混合字符串:
问题也很明显,更复杂的模式,如 Foo2foo12foo1 也能通过筛选器。这就是我遇到困难的地方。
回顾一下:
:
$test = '123_123_Foo'
起初我采用了两种不同的方法,其中一种使用preg_match_all()
:
$test2 = '123_1256_Foo';
preg_match_all('/[0-9]{1,}/', $test2, $matches);
print_r($matches[0]); // Result: 'Array ( [0] => 123 [1] => 1256 )'
和其他使用 preg_replace()
和 explode()
的技术:
$test = preg_replace('/[^0-9_]/', '', $test);
$output = array_filter(explode('_', $test));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
只要字符串不包含混合字母数字的字符,任何一种都可以很好地工作:
$test2 = '123_123_234_Foo2'
显而易见的结果是数组([0]=>123 [1]=>1256 [2]=>2) 所以我写了另一个正则表达式来消除混合字符串:
$test2 = preg_replace('/([a-zA-Z]{1,}[0-9]{1,}[a-zA-Z]{1,})|([0-9]{1,}[a-zA-Z]{1,}[0-9]{1,})|([a-zA-Z]{1,}[0-9]{1,})|([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', '', $test2);
$output = array_filter(explode('_', $test2));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
问题也很明显,更复杂的模式,如 Foo2foo12foo1 也能通过筛选器。这就是我遇到困难的地方。
回顾一下:
- 从字符串中提取可变数量的数字块。
- 字符串至少包含一个数字,并且可能包含由下划线分隔的其他数字和字母。
- 仅提取未在字母前面或后面的数字。
- 仅第一半字符串中的数字有意义。
preg_split()
按字母或混合数字字母的第一个出现位置进行拆分:$test2 = '123_123_234_1Foo2'
$output = preg_split('/([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', $test, 2);
preg_match_all('/[0-9]{1,}/', $output[0], $matches);
print_r($matches[0]); // Results: 'Array ( [0] => 123 [1] => 123 [2] => 234 )'
我的问题的核心是,是否有更简单、更安全、更高效的方法来实现这个结果。
$test2 = "123_123_234_1Foo2"; $ints = array_filter(explode('_', $test2 ), 'is_numeric'); var_dump($ints);
- Emilio Gort