my_string = '(VAT code) address (address) 034372 350-352 Vo Van Kiet, Co Giang Ward'
My current code=
preg_replace('/[^0-9]/', '',my_string)
My current result = 034372350352 This is the wrong output
But I need the correct result = 034372
How to get the first sequence of numbers in a string using php?
Thanks
You're right, I'm on the phone. You should consider doing some validation and error handling on this. Maybe this example helps with that.
You can use preg_match to do this. If you pass the third argument ($matches) to preg_match, it will create an array filled with search results, and $matches[0] will contain the first instance of text that matches the full pattern.
If there may be no digits in the string, you can use an if statement like the following to identify these cases:
Seehttps://www.php.net/manual/ en/function.preg-match.php