搜尋

首頁  >  問答  >  主體

我如何透過php取得字串的第一個數字序列?

my_string = '(增值稅代碼)地址(地址)034372 350-352 Vo Van Kiet, Co Giang Ward'

我目前的程式碼=

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

我目前的結果 = 034372350352 這是錯誤的輸出

但我需要正確的結果 = 034372

如何使用 php 取得字串中的第一個數字序列?

謝謝

P粉014218124P粉014218124565 天前721

全部回覆(2)我來回復

  • P粉231112437

    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);

    你是對的,我正在打電話。您應該考慮對此進行一些驗證和錯誤處理。也許這個例子有助於實現這一點。

    回覆
    0
  • P粉001206492

    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

    您可以使用 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

    回覆
    0
  • 取消回覆