【发布时间】:2017-10-25 15:58:49
【问题描述】:
我正在编写一个 PHP 函数来从如下字符串中提取数字 ID:
$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'
明显的结果是 Array ( [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 这样更复杂的模式会通过过滤器。这就是我有点卡住的地方。
回顾:
- 从字符串中提取数量不定的数字块。
- 该字符串至少包含 1 个数字,并且可能包含其他数字 和用下划线分隔的字母。
- 只能提取前面或后面没有字母的数字。
- 只有字符串前半部分的数字很重要。
由于只需要前半部分,我决定将第一次出现的字母或混合数字字母与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 )'
我的问题的重点是是否有更简单、更安全或更有效的方法来实现这一结果。
【问题讨论】:
-
所以你想只提取完全是数字的下划线分隔的子字符串并拒绝其他所有内容?
-
这样的? eval.in/886873 - 我没有发布答案,因为如果我理解你问题的措辞,我不是 100%。
-
$test2 = "123_123_234_1Foo2"; $ints = array_filter(explode('_', $test2 ), 'is_numeric'); var_dump($ints);