[英]PHP: Get value from string with preg_match, limited characters
對不起標題,我不知道如何更好地解釋它。
我必須從以下字符串中獲取354607 :
...jLHoiAAD1037 354607 Ij0Ij1Ij2...
“354607”是動態的,但在任何情況下它之前都有“1037”,並且在任何情況下都是 6 個字符長。
問題是,字符串大約有 50.000 到 1.000.000 個字符長。 所以我想要一個資源友好的解決方案。
我試過:
preg_match_all("/1037(.*?){0,5}/", $new, $search1037);
和:
preg_match_all("/1037(.*?{0,5})/", $new, $search1037);
但是,我不知道如何正確使用正則表達式。
我希望有人可以幫助我!
非常感謝!
使用,\\d{6}代表6個數字
preg_match_all("/1037(\d{6})/", $new, $search1037);
返回一個數組
array(
0 => array(
0 => 1037354607
),
1 => array(
0 => 354607
)
)
檢查這個演示
由於您關心的是尋找資源友好的解決方案,因此最好不要使用preg_match
。 正則表達式通常需要更多的開銷,如this SO question中所述。
相反,您可以使用strstr()
:
$string = strstr($string,'1037');
這將返回$string
中 '1037' 的第一個實例,以及它后面的所有內容。 然后,使用substr()
:
$string = substr($string,4,6);
它返回$string
從位置 4 開始的子$string
(其中位置 0 = 1
,位置 1 = 0
,位置 2 = 3
,位置 3 = 7
,位置 4 = 6 個數字的開頭)並包括 6 個字符。
為了好玩,在一行中:
$string = substr(strstr($string,'1037'),4,6);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.