查找字符串中出现但以特定字符开头的字符串数


Find the number of occurring strings within a string but starting with specific character

我的问题类似于这个问题:

如何使用PHP查找字符串中的字符序列模式?

但是我需要扩展正则表达式,以便考虑以_(下划线)开头的字符串。

那么,这个正则表达式'/('S{2,}?)'1+/'是如何扩展以满足我的需求的呢?

字符串'parent_parent_parent.parent'应返回[_parent] => 2

如果您需要"查找所有以下划线开头的重复子字符串",只需将下划线添加到正则表达式中即可:/(_['S]{2,}?)'1+/

试试这个

PHP中有一个名为substr_count的函数也起到了同样的作用。

类似功能:mb_substr_count

$str = "parent_parent_parent.parent";
echo substr_count($str, "_parent"); // 2