/    Sign up×
Community /Pin to ProfileBookmark

how to find the number of occurrances of a string?

Hello

I have some very long text
I need to count the number of times the phrase ‘Num photos’
appears in the global text (stored in variable $content)

Is there an efficient way to do this without resorting to parsing?

regards

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@LiLcRaZyFuZzYNov 17.2005 — how long is long?
Copy linkTweet thisAlerts:
@jasongrauthorNov 17.2005 — well, think of a 50MB file of text

This is part of a larger problem I am facing.

Maybe you can take a look at: http://www.webdeveloper.com/forum/showthread.php?t=85673
Copy linkTweet thisAlerts:
@ShrineDesignsNov 17.2005 — [url=http://www.php.net/manual/en/function.substr-count.php]substr_count()[/url]
Copy linkTweet thisAlerts:
@LiLcRaZyFuZzYNov 17.2005 — Can't you split the file?
Copy linkTweet thisAlerts:
@NogDogNov 17.2005 — [code=php]
function count_str_in_file($search, $file, $nocase = FALSE)
# int count_str_in_file(str search, str file[, bool nocase])
{
$handle = @fopen($file, 'r');
if($handle)
{
$i = ($nocase) ? 'i' : ''; # make case-insensitive or not
$search = preg_replace("/([^w_ ])/", "\\$1", $search);
while(!feof($handle))
{
$line = fgets($handle, 4096);
$count += preg_match("/$search/$i", $line, $matches);
}
fclose($handle);
return($count);
}
return(FALSE); # could not read file
}
[/code]

Note: will not count occurences of search string if it is broken across 2 or more lines.
×

Success!

Help @jasongr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.22,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...