简体   繁体   English

如何使用PHP的正则表达式获得所有这种模式的出现?

[英]How can I get all occurrences of this pattern with the regex of PHP?

How can I get, into an array, all occurrences of this pattern 4321[5-9][7-9]{6} but excluding, for example, the occurrences where there is a digit immediately before the value, or immediately after it? 如何将模式4321 [5-9] [7-9] {6}的所有出现都放入数组中,但不包括例如值之前或之后有一个数字的出现?

For instance, 43217999999 should be valid but 1 43217999999 (note the number 1 at the beginning) should not be valid. 例如,43217999999应该有效,但是1 43217999999(注意开头的数字1 )应该无效。

As the first example, 43217999999 1 shouldn't be valid because of the 1 that it has in the end. 作为第一个示例,43217999999 1不应有效,因为它最后有1

The added difficulty, at least for me, is that I have to parse this in whatever position I can find it inside a string. 至少对我来说,增加的困难是,我必须解析它在字符串中可以找到的任何位置。

The string looks like this, literally: 字符串看起来像这样,从字面上看:

43217999997 / 5 43217999999 // 43217999998 _ 43217999999a43216999999-43216999999 arandomword 43215999999 7 5分之4321799999743217999999 // 43217999998 _ 43217999999a43216999999-43216999999 arandomword 43215999999 7

As you would be able to note, it has no standard way of separating the values (I marked in bold the values that would make it invalid, so I shouldn't match those) 正如您将注意到的那样,它没有标准的分隔值的方法(我用粗体标记了将使其无效的值,因此我不应该将其匹配)

My idea right now is something like this: 我现在的想法是这样的:

(\D+|^)(4321[5-9][7-9]{6})(\D+|$)

(\\D+|^) meaning that I expect in that position the start of the string or at least one non-digit and (\\D+|$) meaning that I expect there the end of the string or at least one non-digit. (\\ D + | ^)表示我希望在该位置字符串的开头或至少一个非数字,而(\\ D + | $)表示我希望在那里的字符串结尾或至少一个非数字。

That obviously doesn't do what I picture in my head. 那显然不符合我的脑海。

I also tried do it in two steps, first: 我也尝试分两个步骤进行操作:

preg_match_all("/\D+4321[5-9][7-9]{6}\D+|4321[5-9][7-9]{6}\D+|4321[5-9][7-9]{6}$/", $input, $outputArray);

and then: 接着:

for($cont = 0; $cont < count($outputArray); $cont++) {
   preg_match("/4321[5-9][7-9]{6}/", $outputArray[0][$cont], $outputArray2[]);
}

so I can print 这样我就可以打印

echo "<pre>" . print_r($outputArray2, true) . "</pre>";

but that doesn't let me exclude the ones that have a number before the start of the value ( 5 432157999999 for example), and then, I am not making any progress with my idea. 但这不能让我排除在值开头之前有数字的数字(例如5 432157999999),然后,我的想法没有任何进展。

Thanks in advance for any help. 在此先感谢您的帮助。

If you literally want to check if there is no digit before or after the match you can use negative look ahead and look behind. 如果您确实想检查比赛前后是否没有数字,可以使用负向前看和向后看。

  • (?![0-9]) at the end means: "is not followed by 0-9" (?![0-9])的末尾表示:“不跟0-9”
  • (?<![0-9]) at the start means: "is not preceded by 0-9" (?<![0-9])开头表示:“不以0-9开头”

See this example https://regex101.com/r/6xbmJk/1 看到这个例子https://regex101.com/r/6xbmJk/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM