如何根据条件在字符串中查找特定数字
How can I Find specific numbers in a string based on a criteria
我只想 return 个不符合此条件的号码。
标准的一个例子是 Apt 2,Department 4 等
下面的代码是我一直在尝试的代码,但它不起作用。
结果应该与输出结果相同 preg_match_all('!\d!', $string, $matches);
我希望输出一个包含 2 3 4 4 5 4 5 2 3 2 的数组。它应该不包括 Apt 92 的号码和 Block 5 中的号码。
$string = "23 St John Apt 92 rer 4, Wellington Country Block 5 No value test 4545 tt 232";
preg_match_all('!\d(^((?:Apartment|Apt|Block|Department|Lot|Number|Villa)\s*)([0-9]+))!', $string, $matches);
var_dump($matches);
你试过了吗preg_match_all('/\d+/', $string, $matches);
?
您可以匹配您需要的内容,然后使用(*SKIP)(?!)
(或(*SKIP)(*F)
,或(*SKIP)(*FAIL)
)构造来跳过当前匹配的索引:
$re = '/\b(?:Apartment|Apt|Block|Department|Lot|Number|Villa)\s*[0-9]+(*SKIP)(?!)|\d+/';
$str = "23 St John Apt 92 rer 4, Wellington Country Block 5 No value test 4545 tt 232";
preg_match_all($re, $str, $matches);
见regex demo and PHP demo
输出:
Array
(
[0] => 23
[1] => 4
[2] => 4545
[3] => 232
)
我只想 return 个不符合此条件的号码。 标准的一个例子是 Apt 2,Department 4 等
下面的代码是我一直在尝试的代码,但它不起作用。 结果应该与输出结果相同 preg_match_all('!\d!', $string, $matches);
我希望输出一个包含 2 3 4 4 5 4 5 2 3 2 的数组。它应该不包括 Apt 92 的号码和 Block 5 中的号码。
$string = "23 St John Apt 92 rer 4, Wellington Country Block 5 No value test 4545 tt 232";
preg_match_all('!\d(^((?:Apartment|Apt|Block|Department|Lot|Number|Villa)\s*)([0-9]+))!', $string, $matches);
var_dump($matches);
你试过了吗preg_match_all('/\d+/', $string, $matches);
?
您可以匹配您需要的内容,然后使用(*SKIP)(?!)
(或(*SKIP)(*F)
,或(*SKIP)(*FAIL)
)构造来跳过当前匹配的索引:
$re = '/\b(?:Apartment|Apt|Block|Department|Lot|Number|Villa)\s*[0-9]+(*SKIP)(?!)|\d+/';
$str = "23 St John Apt 92 rer 4, Wellington Country Block 5 No value test 4545 tt 232";
preg_match_all($re, $str, $matches);
见regex demo and PHP demo
输出:
Array
(
[0] => 23
[1] => 4
[2] => 4545
[3] => 232
)