簡體   English   中英

如何獲取特定字符串之后的所有字符串到PHP數組中

[英]How to get all string which are after a specific string into an array in php

我有這樣的字符串,

$string = "You have to know [#4], [#2] and [#5] too";

我想將字符串[[#]之后的所有值放入數組中。

我正在使用一種方法,並且正在工作。 但是,如果有純文本並且沒有“ []”,那么它將給出錯誤。

我正在使用這種方法,

$search_string = "[";
    $count = 0;
    $ids = array();

    for ($i = 0; $i < strlen($string); $i++) {
        $position = strpos($string, $search_string , $count);
        if ($position == $count) {
            $ids[] = $string[$position + 2];
        }
        $count++;
    }

有什么辦法使它合適嗎?

我的目標是將數字放入字符串[[#]之后的$ ids數組中,如果沒有括號,則count($ ids)將為0

當您在某些目標字符串中尋找特定模式時,一種常見的方法是采用preg_match_all()函數。 例如:

$string = "You have to know [#4], [#2] and [#5] too";
$ids = [];
preg_match_all('/\\[#(\d+)[^]]*]/', $string, $ids);

print_r($ids[1]);

在這種情況下,使用模式/\\[#\\d+([^]]*)]/ 它匹配所有以[#開頭,后跟至少一位數字,再跟任意數量的非]字符,再跟]所有序列。 使用捕獲組時,您要查找的值存儲在$ids[1]

請注意,對於沒有任何目標序列的字符串,將沒有匹配項,因此$ids[1]將是一個空數組-看起來就是您想要的。

另請注意,如果您只想計算匹配數,則甚至不需要提供$ids作為preg_match_all參數-只需使用其返回值即可:

$string = "You have to know [#4], [#2] and [#5] too";
var_dump( preg_match_all('/\\[#([^]]+)]/', $string) ); // int(3)
$re = '/\[#(?P<digit>\d+)]/';
$str = 'You have to know [#4], [#2] and [#5] too';

preg_match_all($re, $str, $matches);

var_dump($matches['digit']);

暫無
暫無

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

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