cppit
cppit

Reputation: 4564

php preg_match to return the count

I have these following variables:

$texttofind = "story of a test";
$paragraph  = "the story of a test and a test paragraph used for
               testing the story of a test paragraph";

I would like to use preg_match(); to return the count, which in this case would be 2. any ideas?

Upvotes: 0

Views: 2486

Answers (1)

phihag
phihag

Reputation: 287835

There is no need for regular expressions, simply use substr_count:

echo 'Found texttofind ' . substr_count($paragraph, $texttofind) . ' times';

If you really want to use regular expressions, you can use the following (slower, and unnecessarily complex) expression:

echo preg_match_all('/' . preg_quote($texttofind, '/') . '/', $paragraph);

Upvotes: 8

Related Questions