我正在编写一个 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 这样更复杂的模式会通过过滤器。这就是我有点卡住的地方。
回顾:
- 从字符串中提取可变数量的数字 block 。
- 该字符串至少包含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 )'
我的问题的重点是是否有更简单、更安全或更有效的方法来实现这一结果。
最佳答案
如果我对你的问题的理解正确,你想拆分一个下划线分隔的字符串,并过滤掉任何非数字的子字符串。如果是这样,这可以在没有正则表达式的情况下实现,使用 explode()
, array_filter()
和 ctype_digit()
;例如:
<?php
$str = '123_123_234_1Foo2';
$digits = array_filter(explode('_', $str), function ($substr) {
return ctype_digit($substr);
});
print_r($digits);
这会产生:
Array
(
[0] => 123
[1] => 123
[2] => 234
)
注意 ctype_digit()
:
Checks if all of the characters in the provided string are numerical.
所以 $digits
仍然是一个字符串数组,尽管是数字。
希望这有帮助:)
关于PHP从字符串中提取数字 block 时如何避免混合字母数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937044/