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
P粉2311124372023-09-10 09:31:03
<?php // make a service class or trait or package with a format enum by country could be useful. Also if you add the functionality to implement it into Laravel. class VatService { function getVatId(string $hayStack, string $needle = '/\d+/', bool $validateCount = false, $count = 6): string { return ( preg_match($needle, $hayStack, $matches) && ( $count == strlen($matches[0])) && $validateCount ) ? $matches[0] : throw new Exception('VaT number was not found : ' . $count . ' == ' . strlen($matches[0]) . ' ' . $matches[0] ); } }
$myString = '(VAT code) Địa chỉ (Address) 034372 350-352 Võ Văn Kiệt, Phường Cô Giang'; echo getVatId(hayStack: $myString, validateCount: true, count: 6);
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.
P粉0012064922023-09-10 09:11:13
$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 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:
if (preg_match($pattern, $my_string, $matches)) { echo $matches[0]; } else { echo "No match found"; }
Seehttps://www.php.net/manual/ en/function.preg-match.php