php子字符串计数找到很多单词 [英] php sub string count find many words

查看:24
本文介绍了php子字符串计数找到很多单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php

<?php
$tt1="b a b c";
echo substr_count($tt1,"a"or"b");
?>

由于单词有 a 和 b,我希望结果为 3.我试图将输出设为 3.但我得到的是 0.请帮忙

Since the word has both a and b i want the result as three.I am trying to get the output as 3.But i am getting 0.please help

推荐答案

substr_count 只会寻找一个子串.

substr_count will just look for one substring.

  • 你不能让它一次搜索两个字符串.
  • 如果您真的想要,最简单的选择就是调用它两次.(参见 RiggsFollys 的回答.)

较短的选项是使用 preg_match_all 代替(返回计数):

The shorter option would be using preg_match_all instead (returns the count):

$count = preg_match_all("/a|b/", $tt1);

(它也只是遍历字符串一次寻找替代品.更容易适应更多的子字符串.可能会寻找词 \b 边界等.但只有当你听说过/读过正则表达式时才建议之前.)

(Which also just traverses the string once looking for alternatives. Easier to adapt for more substrings. May look for word \b boundaries etc. But only advisable if you've heard/read about regexps before.)

这篇关于php子字符串计数找到很多单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆