How can I get the first sequence of numbers of a string via php?
P粉014218124
P粉014218124 2023-09-09 10:11:24
0
2
644

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粉014218124
P粉014218124

reply all(2)
P粉231112437
<?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粉001206492
$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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template