我有一个这样的字符串,
$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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句