我正试图编写正则表达式来搜索字符串中的图像标签,然后使用'count'或'substr_count'来计数它们
, [image1], [image2]等等. .
我对正则表达式是一个绝对的新手,所以它对我来说很困惑。在有人问之前,是的,我对此做了一些研究,但我只是好奇,是否有什么捷径是我和其他读到这篇文章的人可能会错过的。
我也找到了https://regex101.com/,但是我不知道从那里去哪里。
我对上面例子的努力是:
'~('[image(['d])+']~i'
和.
'#[^a-z0-9.]#i'
如果有人能告诉我如何搜索上面的内容,或者给我指出一个编程金矿的正确方向,那将是非常感激的。
欢呼,丰富的
使用preg_match_all,例如:
$string = <<< LOL
some text with image1 and another
part of that contains image2
yet another image3
LOL;
preg_match_all('/(image'd+)/i', $string, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[1]); $i++) {
echo $matches[1][$i]."'n";
}
输出:
image1
image2
image3
演示:
http://ideone.com/cQymaV
preg_match_all
函数已经返回了出现的次数,您不需要使用count或其他东西:
if (false !== $count = preg_match_all('~'[image'd+]~i', $text))
echo $count;