Home How do I check if a string contains a specific word?
Reply: 30

# How do I check if a string contains a specific word?

Charles Yeung
1#
Charles Yeung Published in 2010-12-06 13:14:05Z
 Consider: $a = 'How are you?'; if ($a contains 'are') echo 'true';  Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')? Massimiliano Kraus 2# Massimiliano Kraus Reply to 2017-08-07 13:49:38Z  You can use the strpos() function which is used to find the occurrence of one string inside another one: $a = 'How are you?'; if (strpos($a, 'are') !== false) { echo 'true'; }  Note that the use of !== false is deliberate; strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').
Milan Babuškov
3#
Milan Babuškov Reply to 2010-12-06 13:15:31Z
 Use strpos function: if (strpos($a, 'are') !== false) echo 'true';  Breezer 4# Breezer Reply to 2018-01-20 09:52:28Z  You could use regular expressions, it's better for word matching compared to strpos as mentioned by other users it will also return true for strings such as fare, care, stare etc. This can simply be avoided in the regular expression by using word boundaries. A simple match for are could look something like this: $a = 'How are you?'; if (preg_match('/\bare\b/',$a)) echo 'true';  On the performance side, strpos is about three times faster and have in mind, when I did one million compares at once, it took preg match 1.5 seconds to finish and for strpos it took 0.5 seconds. Peter Mortensen 5# Peter Mortensen Reply to 2013-09-24 18:28:24Z  Look at strpos():   Funk Forty Niner 6# Funk Forty Niner Reply to 2015-05-07 01:44:51Z  To determine whether a string contains another string you can use the PHP function strpos(). int strpos ( string$haystack , mixed $needle [, int$offset = 0 ] )   CAUTION: If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a == compare that will not work, you will need to do a === A == sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right. A === sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.
Peter Mortensen
7#
Peter Mortensen Reply to 2013-09-24 18:31:57Z
 Using strstr() or stristr() if your search should be case insensitive would be another option.
ejunker
8#
ejunker Reply to 2011-08-18 18:54:47Z
 Here is a little utility function that is useful in situations like this // returns true if $needle is a substring of$haystack function contains($needle,$haystack) { return strpos($haystack,$needle) !== false; } 
YashG99
9#
YashG99 Reply to 2012-08-20 16:20:31Z
 Another option is to use the strstr() function. Something like: if (strlen(strstr($haystack,$needle))>0) { // Needle Found }  Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
Dávid
10#
Dávid Reply to 2012-10-09 16:17:30Z
 $a = 'how are you'; if (strpos($a,'are')) { echo 'true'; } 
Alan Piralla
11#
Alan Piralla Reply to 2013-07-09 08:38:53Z
 If you want to avoid the "falsey" and "truthy" problem, you can use substr_count: if (substr_count($a, 'are') > 0) { echo "at least one 'are' is present!"; }  It's a bit slower than strpos but it avoids the comparison problems. Jason OOO 12# Jason OOO Reply to 2015-05-18 10:45:06Z  The function below also works and does not depend on any other function; it uses only native PHP string manipulation. Personally, I do not recommend this, but you can see how it works:  1) { for ($i = 0; $i <$string_length; $i++) { /* the remaining part of the string is equal or greater than the keyword */ if (($string_length + 1 - $i) >=$keyword_length) { // Check if keyword's first char == string's first char if ($keyword_first_char ==$string[$i]) {$match = 1; for ($j = 1;$j < $keyword_length;$j++) { if (($i +$j < $string_length) &&$keyword[$j] ==$string[$i +$j]) { $match++; } else { return false; } } if ($match == $keyword_length) { return true; } // end if first match found } // end if remaining part } else { return false; } // end for loop } // end case4 } return false; } }  Test: var_dump(is_str_contain("test", "t")); //true var_dump(is_str_contain("test", "")); //false var_dump(is_str_contain("test", "test")); //true var_dump(is_str_contain("test", "testa")); //flase var_dump(is_str_contain("a----z", "a")); //true var_dump(is_str_contain("a----z", "z")); //true var_dump(is_str_contain("mystringss", "strings")); //true  joan16v 13# joan16v Reply to 2015-12-23 14:00:42Z  if (preg_match('are',$a)) { echo 'true'; } 
Amal Murali
14#
Amal Murali Reply to 2014-05-25 03:49:35Z
 Make use of case-insensitve matching using stripos(): if (stripos($string,$stringToSearch) !== false) { echo 'true'; } 
Peter Mortensen
15#
Peter Mortensen Reply to 2016-06-25 19:30:52Z
 Another option to finding the occurrence of a word from a string using strstr() and stristr() is like the following:  
Peter Mortensen
16#
Peter Mortensen Reply to 2016-06-25 19:30:08Z
 I had some trouble with this, and finally I chose to create my own solution. Without using regular expression engine: function contains($text,$word) { $found = false;$spaceArray = explode(' ', $text);$nonBreakingSpaceArray = explode(chr(160), $text); if (in_array($word, $spaceArray) || in_array($word, $nonBreakingSpaceArray) ) {$found = true; } return $found; }  You may notice that the previous solutions are not an answer for the word being used as a prefix for another. In order to use your example: $a = 'How are you?'; $b = "a skirt that flares from the waist";$c = "are";  With the samples above, both $a and $b contains $c, but you may want your function to tell you that only $a contains $c. guillaumepotier 17# guillaumepotier Reply to 2014-04-05 11:49:13Z  Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster. (http://in2.php.net/preg_match) if (strpos($text, 'string_name') !== false){ echo 'get the string'; } 
Carlos Campderrós
18#
Carlos Campderrós Reply to 2017-01-22 14:39:58Z
 While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring. What's the difference? Substrings can appear within other words: The "are" at the beginning of "area" The "are" at the end of "hare" The "are" in the middle of "fares" One way to mitigate this would be to use a regular expression coupled with word boundaries (\b): function containsWord($str,$word) { return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i',$str); }  This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W), which are going to be anything that isn't a-z, A-Z, 0-9, or _. That means digits and underscores are going to be counted as word characters and scenarios like this will fail: The "are" in "What _are_ you thinking?" The "are" in "lol u dunno wut those are4?" If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).
eFarzad
19#
eFarzad Reply to 2017-12-24 11:14:57Z
 Peer to SamGoody and Lego Stormtroopr comments. If you are looking for a PHP algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only: Issues with the other boolean search methods such as strpos(), preg_match(), strstr() or stristr() can't search for multiple words results are unranked PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency): It sounds difficult but is surprisingly easy. If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them? If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our results by the ones that best match the query. This is the idea of the vector space model, not far from how SQL full-text search works: function get_corpus_index($corpus = array(),$separator=' ') { $dictionary = array();$doc_count = array(); foreach($corpus as$doc_id => $doc) {$terms = explode($separator,$doc); $doc_count[$doc_id] = count($terms); // tf–idf, short for term frequency–inverse document frequency, // according to wikipedia is a numerical statistic that is intended to reflect // how important a word is to a document in a corpus foreach($terms as $term) { if(!isset($dictionary[$term])) {$dictionary[$term] = array('document_frequency' => 0, 'postings' => array()); } if(!isset($dictionary[$term]['postings'][$doc_id])) { $dictionary[$term]['document_frequency']++; $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0); }$dictionary[$term]['postings'][$doc_id]['term_frequency']++; } //from http://phpir.com/simple-search-the-vector-space-model/ } return array('doc_count' => $doc_count, 'dictionary' =>$dictionary); } function get_similar_documents($query='',$corpus=array(), $separator=' '){$similar_documents=array(); if($query!=''&&!empty($corpus)){ $words=explode($separator,$query);$corpus=get_corpus_index($corpus,$separator); $doc_count=count($corpus['doc_count']); foreach($words as$word) { if(isset($corpus['dictionary'][$word])){ $entry =$corpus['dictionary'][$word]; foreach($entry['postings'] as $doc_id =>$posting) { //get term frequency–inverse document frequency $score=$posting['term_frequency'] * log($doc_count + 1 /$entry['document_frequency'] + 1, 2); if(isset($similar_documents[$doc_id])){ $similar_documents[$doc_id]+=$score; } else{$similar_documents[$doc_id]=$score; } } } } // length normalise foreach($similar_documents as$doc_id => $score) {$similar_documents[$doc_id] =$score/$corpus['doc_count'][$doc_id]; } // sort from high to low arsort($similar_documents); } return$similar_documents; }  CASE 1 $query = 'are';$corpus = array( 1 => 'How are you?', ); $match_results=get_similar_documents($query,$corpus); echo ' '; print_r($match_results); echo '
';  RESULT Array ( [1] => 0.52832083357372 )  CASE 2 $query = 'are';$corpus = array( 1 => 'how are you today?', 2 => 'how do you do', 3 => 'here you are! how are you? Are we done yet?' ); $match_results=get_similar_documents($query,$corpus); echo ' '; print_r($match_results); echo '
';  RESULTS Array ( [1] => 0.54248125036058 [3] => 0.21699250014423 )  CASE 3 $query = 'we are done';$corpus = array( 1 => 'how are you today?', 2 => 'how do you do', 3 => 'here you are! how are you? Are we done yet?' ); $match_results=get_similar_documents($query,$corpus); echo ' '; print_r($match_results); echo '
';  RESULTS Array ( [3] => 0.6813781191217 [1] => 0.54248125036058 )  There are plenty of improvements to be made but the model provides a way of getting good results from natural queries, which don't have boolean operators such as strpos(), preg_match(), strstr() or stristr(). NOTA BENE Optionally eliminating redundancy prior to search the words thereby reducing index size and resulting in less storage requirement less disk I/O faster indexing and a consequently faster search. 1. Normalisation Convert all text to lower case 2. Stopword elimination Eliminate words from the text which carry no real meaning (like 'and', 'or', 'the', 'for', etc.) 3. Dictionary substitution Replace words with others which have an identical or similar meaning. (ex:replace instances of 'hungrily' and 'hungry' with 'hunger') Further algorithmic measures (snowball) may be performed to further reduce words to their essential meaning. The replacement of colour names with their hexadecimal equivalents The reduction of numeric values by reducing precision are other ways of normalising the text. RESOURCES http://linuxgazette.net/164/sephton.html http://snowball.tartarus.org/ MySQL Fulltext Search Score Explained http://dev.mysql.com/doc/internals/en/full-text-search.html http://en.wikipedia.org/wiki/Vector_space_model http://en.wikipedia.org/wiki/Tf%E2%80%93idf http://phpir.com/simple-search-the-vector-space-model/
John Slegers
20#
John Slegers Reply to 2016-02-21 18:25:42Z
 You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit): echo FALSE === strpos($a,'are') ? 'false': 'true';  Pratik C Joshi 21# Pratik C Joshi Reply to 2015-09-08 11:00:06Z  You should use case Insensitive format,so if the entered value is in small or caps it wont matter.   Here stripos finds needle in heystack without considering case (small/caps). PHPCode Sample with output KsaR 22# KsaR Reply to 2016-03-20 17:38:15Z  The short-hand version $result = false!==strpos($a, 'are');  Peter Mortensen 23# Peter Mortensen Reply to 2016-06-25 19:26:54Z  Maybe you could use something like this:   Peter Mortensen 24# Peter Mortensen Reply to 2016-06-25 19:25:09Z  In order to find a 'word', rather than the occurrence of a series of letters that could in fact be a part of another word, the following would be a good solution. $string = 'How are you?'; $array = explode(" ",$string); if (in_array('are', $array) ) { echo 'Found the word'; }  Community 25# Community Reply to 2017-05-23 12:34:57Z  I'm a bit impressed that none of the answers here that used strpos, strstr and similar functions mentioned Multibyte String Functions yet (2015-05-08). Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with mb_. Therefore, the accepted answer would use mb_strpos or mb_stripos (for case-insensitive matching) instead: if (mb_strpos($a,'are') !== false) { echo 'true'; }  If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the mb_ functions. A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.
Akshay Khale
26#
Akshay Khale Reply to 2017-01-05 14:16:57Z
 The strpos function works fine, but if you want to do case-insensitive checking for a word in a paragraph then you can make use of the stripos function of PHP. For example, $result = stripos("I love PHP, I love PHP too!", "php"); if ($result === false) { // Word does not exist } else { // Word exists }  Find the position of the first occurrence of a case-insensitive substring in a string. If the word doesn't exist in the string then it will return false else it will return the position of the word.
Peter Mortensen
27#
Peter Mortensen Reply to 2017-05-21 11:26:37Z
 You can use the strstr function: $haystack = "I know programming";$needle = "know"; $flag = strstr($haystack, $needle); if ($flag){ echo "true"; }  Without using an inbuilt function: $haystack = "hello world";$needle = "llo"; $i =$j = 0; while (isset($needle[$i])) { while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) { $j++;$i = 0; } if (!isset($haystack[$j])) { break; } $i++;$j++; } if (!isset($needle[$i])) { echo "YES"; } else{ echo "NO "; } 
mvw
28#
mvw Reply to 2015-09-23 23:37:08Z
 Check if string contains specific words? This means the string has to be resolved into words (see note below). One way to do this and to specify the separators is using preg_split (doc):   A run gives $php -f test.php string 'How are you?' contains word 'are' string 'How are you?' does not contain word 'ar' string 'How are you?' does not contain word 'hare'  Note: Here we do not mean word for every sequence of symbols. A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters. A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl " word ". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (..) Peter Mortensen 29# Peter Mortensen Reply to 2016-06-25 19:17:33Z  If you want to check if the string contains several specifics words, you can do: $badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat"); $string = "a string with the word ivoire";$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i",$string, $matches); if ($matchFound) { echo "a bad word has been found"; } else { echo "your string is okay"; }  This is useful to avoid spam when sending emails for example.
Charles Clayton
30#
Charles Clayton Reply to 2016-07-13 03:41:47Z
 A string can be checked with the below function: function either_String_existor_not($str,$character) { if (strpos($str,$character) !== false) { return true; } return false; } 
Peter Mortensen
31#
Peter Mortensen Reply to 2016-06-25 19:14:55Z
 Another solution for a specific string: $subject = 'How are you?';$pattern = '/are/'; preg_match($pattern,$subject, $match); if ($match[0] == 'are') { echo true; }  You can also use strpos() function.
 You need to login account before you can post.
Processed in 0.407405 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO