如何将特定字符串后面的所有字符串都放入php中的数组中

问题描述 投票:0回答:2

我有这样的字符串,

$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

php arrays string
2个回答
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)

0
投票
$re = '/\[#(?P<digit>\d+)]/';
$str = 'You have to know [#4], [#2] and [#5] too';

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

var_dump($matches['digit']);
© www.soinside.com 2019 - 2024. All rights reserved.