How to check if a string contains specific words in PHP |
X

Congrats, You are Subscribed to Receive Updates.

How to check if a string contains specific words in PHP


How to check if a string contains specific words in PHP. In PHP, while working with Strings and file read operations, we have to check whether a word exist or not. And sometimes you need to do one more step to get the word count. In certain situations, you need to find multiple words.

php-kvcodes

I have some codes, for your reference, to understand and create your own code. Let’s start with example code.

<?php
$kvcodes = 'This is a sample text, to test the string manupluations, especially, the strpos, and the preg_match, and the regrex functions' ; 

if (strpos($kvcodes,'string') !== false) {
    echo 'Yes, the string found in the above sentence';
} else {
    echo ' No, the string doesnot exist in the sentence' ;
}

The above code, helps you to find the ‘string’ in the $kvcodes.  and if it found, it prints the words, is found. Else it wont work. This is one of a simplest way to find the word appearance, But this will be limited, you can test one string at a time. I mean, you can find only one string matching positions at a time.

If you want to test more than one string matching’s go with preg_match. Which will helps you to check more than one matching at a time.  Here is the example code,

if(preg_match('[the|string]', $kvcodes) === true) { 
    echo " the word found in it" ;
}

Another way is, str_count , this will get the total string occurrence counts,  Here is an example code.

// Another method ....

$str_counts =substr_count($kvcodes, 'the'); 
if ($str_counts  > 0) {
    echo "The word exist and its occurrence count is". $str_counts ;
}

That’s it, you can try either methods, to get proper results, based on the place and necessity.  Comment below for your queries and doubts.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar