簡體   English   中英

PHP-獲取數字,而不是字符串中的char

[英]Php - get number, not char from string

我對php不太熟悉,在這種情況下被困在如何使用substr中:

我必須對具有一些數字和符號的字符串進行解析,例如:

1[2[3,5],4[7[65,9,11],8]]

為此,我使用了a,它將通過並獲取字符串的每個字符,如下所示:

$count = 0;
for($i = 0; $i <= strlen($string); $i++){
    $char = substr($string, $i, 1);
    if($char == '['){
        $count --;
    }
    if($char == ']'){
        $count ++;
    }
    if($count == 0){
        break;
    }

    if(is_numeric(substr($string, $i +1, 1)) and $count == -1){
        $number = substr($string, $i +1, 1);
        $array_aux[] = $number;
    }

}

但是,由於我要輸入char(substr($ string,$ i,1)),它不適用於超過一位的數字,例如65和11

數組的內容類似於:(...,6,5,5,9,1,1,...)

什么時候應該是這樣的:(...,65,9,11,...)

有什么幫助嗎?

抱歉,我認為還不夠清楚。 當count的值為-1時,我需要'['內的數字

(這就是為什么我使用substr並獲取每個字符的原因)

示例:當字符串為:1 [2 [3,5],4 [7 [65,9,11],8]]時,數組必須包含2和4

當字符串為:2 [3,5],4 [7 [65,9,11],8]]時,數組必須包含3和5

當字符串為:7 [65,9,11],8]]時,數組必須包含65、9和11。依此類推...

抱歉,現在才提供這些詳細信息,我當時沒有電腦:(

使用簡單的正則表達式的preg_match_all可以為您做到這一點:

$in = "1[2[3,5],4[7[65,9,11],8]]";
preg_match_all('~\d+~', $in, $out);
print_r($out[0]);

輸出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 4
    [5] => 7
    [6] => 65
    [7] => 9
    [8] => 11
    [9] => 8
)

您可以通過匹配一次或多次而不是數字\\D+來使用preg_split和split

$str = "1[2[3,5],4[7[65,9,11],8]]";
print_r(preg_split("/\D+/", $str, -1, PREG_SPLIT_NO_EMPTY));

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 4
    [5] => 7
    [6] => 65
    [7] => 9
    [8] => 11
    [9] => 8
)

暫無
暫無

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

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