Wie kann ich die erste Zahlenfolge einer Zeichenfolge per PHP erhalten?
P粉014218124
P粉014218124 2023-09-09 10:11:24
0
2
576

my_string = '(VAT-Code) Adresse (Adresse) 034372 350-352 Vo Van Kiet, Co Giang Ward'

Mein aktueller Code =

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

Mein aktuelles Ergebnis = 034372350352 Das ist die falsche Ausgabe

Aber ich brauche das richtige Ergebnis = 034372

Wie erhalte ich mit PHP die erste Zahlenfolge in einer Zeichenfolge?

Danke

P粉014218124
P粉014218124

Antworte allen(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);

你是对的,我正在打电话。您应该考虑对此进行一些验证和错误处理。也许这个例子有助于实现这一点。

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

您可以使用 preg_match 来执行此操作。如果将第三个参数 ($matches) 传递给 preg_match,它将创建一个填充搜索结果的数组,并且 $matches[0] 将包含与完整模式匹配的第一个文本实例。

如果字符串中可能没有数字,您可以使用如下 if 语句来识别这些情况:

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

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

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!