user999489
user999489

Reputation:

Count exact substring in a string in 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';

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');

any idea?

Upvotes: 2

Views: 1796

Answers (3)

yehuda
yehuda

Reputation: 1282

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

Note however that this wont count words next to a comma or fullstop or at the beginning so it might not help you.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

$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);

Upvotes: 2

jeremysawesome
jeremysawesome

Reputation: 7254

It might be cheating, but you could always search for ' sun ' instead of 'sun'. :)

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

Upvotes: 1

Related Questions