【问题标题】:How can I Find specific numbers in a string based on a criteria如何根据条件在字符串中查找特定数字
【发布时间】:2016-05-11 18:12:02
【问题描述】:

我只想返回不符合此条件的数字。 标准的示例是 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);

【问题讨论】:

  • 你完全误解了字符类。你期望什么输出?

标签: regex preg-replace preg-match preg-match-all


【解决方案1】:

您可以匹配您需要的内容,然后使用(*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 demoPHP demo

输出:

Array
(
    [0] => 23
    [1] => 4
    [2] => 4545
    [3] => 232
)

【讨论】:

  • 我怎样才能让它返回所有分成单个数字的数字
  • 去掉末尾的+$re = '/\b(?:Apartment|Apt|Block|Department|Lot|Number|Villa)\s*[0-9]+(*SKIP)(?!)|\d/';
【解决方案2】:

你试过preg_match_all('/\d+/', $string, $matches);吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2021-08-08
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多