簡體   English   中英

如何在 PHP 的字符串數組中獲取某個數值?

[英]How get a certain numeric value inside array of string in PHP?

我有一個字符串$line 例如,

$line = "stringA stringB 4-stringC stringD stringF 12345 stringG 678249 stringH ";

根據 var $line ,字符串有 6 個詞,2 個數值,1 個數字和字符串的組合詞。

我想捕捉某個字符串,它是一個數值12345 這是我剛剛嘗試過的代碼:

if (preg_match('/ ([0-9,]+)/', $line, $matches) === 1 && strlen($matches[0]) > 3 && strlen($matches[1]) > 3) {
    echo var_dump($matches[0]);
}

但是,一旦跟蹤,代碼似乎只采用字符串上的第一個數值。 結果是:

array(2) {
  [0]=>
  string(2) " 4"
  [1]=>
  string(1) "4"
}

而不是12345

那么,如果我只想捕獲字符串包含: 12345 ,我應該使用什么“正則表達式”?

您可以使用單詞邊界\b並使用量詞匹配 4 個或更多數字{4,}

\b\d{4,}\b

例如

$line = "string string 4-string string string 12345 string 678249 string ";
if (preg_match('/\b\d{4,}\b/', $line, $matches)) {
    var_dump($matches);
}

Output

array(1) {
  [0]=>
  string(5) "12345"
}

Php 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM