Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count occurrences of test in string php, not test123 or testabc

i used code:

$text = 'This is test22 is a test11 abc test mlk'
result= substr_count($text, 'test',0,0)

result = 3;

but my desired output = 1;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i just want to count the number of occurrences of the exact word test, not testaaa or test123

Thank you

>Solution :

A string check alone can’t do this. I would use a regex for this. Using word boundaries and preg_match this can be done with:

$text = 'This is test22 is a test11 abc test mlk';
preg_match('/\btest\b/', $text, $result);
echo count($result);

Alternatively preg_replace could be used which has a count feature built into it.

preg_replace('/\btest\b/', '', $text, -1, $count);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading