Search code examples
phpextract

How can i get the first sequence of numbers of string by php?


my_string = ' (VAT code) Địa chỉ (Address) 034372 350-352 Võ Văn Kiệt, Phường Cô Giang'

My current code =

preg_replace('/[^0-9]/', '',my_string)

And my current result = 034372350352 and this's wrong output

But i need correct result = 034372

How can I get the first sequence of numbers in string using php?

Thank you


Solution

  • $my_string  = "(VAT code) Địa chỉ (Address) 034372 350-352 Võ Văn Kiệt, Phường Cô Giang";
    $pattern = "/\d+/";
    preg_match($pattern, $my_string, $matches);
    echo $matches[0]; //Outputs 034372
    

    You can use preg_match to do this. If you pass a third argument ($matches) to preg_match it will create an array filled with the results of search and $matches[0] will contain the first instance of text that matched the full pattern.

    If there is a chance no numbers will be in the string, you can identify those cases with an if statement like this:

    if (preg_match($pattern, $my_string, $matches)) {
        echo $matches[0];
    }
    else {
        echo "No match found";
    }
    

    See https://www.php.net/manual/en/function.preg-match.php