我希望能够在更大的字符串中找到特定字符串的出现次数。
例如,请采取以下措施......
$body = "I love My Dog. I love My cat. What a cat."
$count = substr_count($body, "My cat");
说我正在寻找我的猫。首先,我想找到所有出现的" My Cat",一旦我有了,我想找到所有出现的"我的"然后" cat",要做到这一点我再次运行子串计数但更改针。问题是包含cat和substring count的很多单词会返回所有这些。我有以下正则表达式
if (preg_match('/\\b' . "My cat" . '\\b/', $body)) {
但我不确定如何搜索整个字符串并查找出现次数而不将其分解为数组(这可能很难看到我搜索"我的猫"除了个别条款因此被空格分解将无法发挥作用。
有没有办法使用substring_count或类似函数来查找不属于另一个单词的单个术语的出现次数。
理想情况下,我想要
"My cat" : count 1
"My": count 2
"cat": count 2
感谢。
答案 0 :(得分:0)
这样的事情怎么样?
<?
$body = "I love My Dog. I love My cat. What a cat.";
$search = "My cat";
// Find full string matches
preg_match_all("/[^a-zA-Z]".$search."[^a-zA-Z]/i",$body,$matches);
$found[$search] = count($matches[0]);
// Find individual terms
$search = explode(" ",$search);
foreach($search as $term) {
preg_match_all("/[^a-zA-Z]".$term."[^a-zA-Z]/i",$body,$matches);
$found[$term] = count($matches[0]);
}
// Print results
foreach($found as $term=>$count) {
echo '"'.$term.'": count '.$count."\n";
}
?>
输出:
"My cat": count 1
"My": count 2
"cat": count 2