regex – How get a certain numeric value inside array of string in PHP?-ThrowExceptions

Exception or error:

I have a String $line. For example,

$line = "stringA stringB 4-stringC stringD stringF 12345 stringG 678249 stringH ";

According to the var $line, there are 6 words of string, 2 numeric values, and 1 combination word of numeric and string.

I would like to catch a certain string which is a numeric value 12345. And this is my code that I just tried:

if (preg_match('/ ([0-9,]+)/', $line, $matches) === 1 && strlen($matches[0]) > 3 && strlen($matches[1]) > 3) {
    echo var_dump($matches[0]);

However, It seems like the code only take the first numeric value on the string, once it traced. And the result is:

array(2) {
  string(2) " 4"
  string(1) "4"

instead of 12345.

So, What is the ‘Regular Expression’ should I use, if I only like to catch string contain: 12345 ?

How to solve:

You could use word boundaries \b and match 4 or more digits using a quantifier {4,}


For example

$line = "string string 4-string string string 12345 string 678249 string ";
if (preg_match('/\b\d{4,}\b/', $line, $matches)) {


array(1) {
  string(5) "12345"

Php demo

Leave a Reply

Your email address will not be published. Required fields are marked *