How to match a fixed number of digits with a regular expression in PHP?

I want to get 8 consecutive lines from a line.

"hello world,12345678anything else" 

should return 12345678 as a result (the gap between them is optional).

But this should not return anything:

 "hello world,123456789anything else" 

Since it has 9 digits, I need only 8 digits.

+4
source share
3 answers

Try

 '/(?<!\d)\d{8}(?!\d)/' 
+10
source
 $var = "hello world,12345678798anything else"; preg_match('/[0-9]{8}/',$var,$match); echo $match[0]; 
0
source

You need to match the material on both sides of 8 digits. You can do this with zero-width traversal statements, as the @S Mark example shows, or you can use an easier way to just create a backlink for 8 digits:

 preg_match('/\D(\d{8})\D/', $string, $matches) $eight_digits = $matches[1]; 

But this will not match when numbers start or end with a line or line; for this you need to clarify it a bit:

 preg_match('/(?:\D|^)(\d{8})(?:\D|$)/', $string, $matches) $eight_digits = $matches[1]; 

(?:...) In this case, you can specify a subset of variables using | , not counting the match as a backlink (i.e., adding it to the elements in the $matches array).

For many other details of a rich and subtle language that is the Perl-Compatible Regular Expression syntax, see http://ca3.php.net/manual/en/reference.pcre.pattern.syntax.php

0
source

Source: https://habr.com/ru/post/1305077/


All Articles