skip to Main Content

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 gget the first sequence of numbers of string by php?

Thank you

2

Answers


  1. $firstSetOfNumbers = preg_match("/d+(s|$)/", $string);

    that should be correct.

    Login or Signup to reply.
  2. $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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search