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

时间:2018-06-07 10:17:15

标签: php arrays string

我有一个像这样的字符串,

$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数组,这些数字位于&#34; [#&#34;的字符串之后,如果没有大括号,那么count($ ids)将为0

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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']);