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
<?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);
你是對的,我正在打電話。您應(yīng)該考慮對此進(jìn)行一些驗(yàn)證和錯(cuò)誤處理。也許這個(gè)例子有助于實(shí)現(xiàn)這一點(diǎn)。
$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 來執(zhí)行此操作。如果將第三個(gè)參數(shù) ($matches) 傳遞給 preg_match,它將創(chuàng)建一個(gè)填充搜索結(jié)果的數(shù)組,并且 $matches[0] 將包含與完整模式匹配的第一個(gè)文本實(shí)例。
如果字符串中可能沒有數(shù)字,您可以使用如下 if 語句來識別這些情況:
if (preg_match($pattern, $my_string, $matches)) { echo $matches[0]; } else { echo "No match found"; }