计算PHP字符串中的确切子字符串 [英] Count exact substring in a string in php

查看:87
本文介绍了计算PHP字符串中的确切子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么知道一个字符串中一个子字符串的确切出现次数.例如,考虑以下字符串:

How can I know the exact number of occurences of a substring in a string. For example consider the following string:

$string = 'The sun is bright, what a beatiful sunlight';

当我搜索单词"sun"时,我希望它返回1而不是2.这种情况发生在我这样做时:

when I search for the word 'sun' I want it to return 1 instead of 2. That happens when I do:

$counter = substr_count($string, 'sun');

有什么主意吗?

推荐答案

$wordCounts = array_count_values(str_word_count($string,1));
$sunCount = (isset($wordCounts['sun'])) ? $wordCounts['sun'] : 0;

区分大小写...如果不区分大小写,则可能需要使用带有单词边界的正则表达式

Case-sensitive... if you want case-insensitive, you'll probably need to use a regular expression using word boundaries

$sunCount = preg_match_all('/\bsun\b/i',$string);

这篇关于计算PHP字符串中的确切子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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