Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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')?

share|improve this question
    
Have you ever heard of "preg_match" or "regexps"? – mzcoxfde Nov 3 '16 at 13:53

37 Answers 37

up vote 3837 down vote accepted

You can use the strpos function which is used to find the occurrence of one string inside other:

$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').

share|improve this answer
91  
one thing I found was that if "are" is the first word, then the above code will fail because it returns "0" which can be considered false! To avoid this it should read if(strpos("x".$a,'are') !== false) ..... – Darknight Aug 16 '11 at 16:05
304  
@Darknight: "0" is not considered "false" when you use !==. It is only considered if you use !=. – Milan Babuškov Oct 16 '11 at 9:12
123  
Very late to the party, but be careful with this. This will also return true for the string 'Do you care?' – DTest Sep 28 '12 at 0:01
75  
@DTest - well yes of course it will return true because the string contains 'are'. If you are looking specifically for the word ARE then you would need to do more checks like, for example, check if there is a character or a space before the A and after the E. – jsherk Nov 14 '12 at 21:35
18  
Very good comments above! I never use != or ==, after all !== and === is best option (in my opinion) all aspect considered (speed, accuracy etc). – Melsi Dec 15 '12 at 12:28

You could use regular expressions. It would look something like this:

$a = 'How are you?';

if (preg_match('/are/',$a))
    echo 'true';

Don't tell me it's bad just because you've heard it's bad before. You might if you have any facts to back it up though ;)

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. What I'm trying to say is that it runs really fast either way. If you don't have 100,000 visitors every second, you shouldn't concern yourself with this kind of stuff and take what's most comfortable, IMO.

share|improve this answer
8  
thanks for the suggestion, your code works great, but I prefer to use strpos function. – Charles Yeung Dec 6 '10 at 13:26
8  
@Alexander.Plutov second of all you're giving me a -1 and not the question ? cmon it takes 2 seconds to google the answer google.com/… – Breezer Dec 6 '10 at 14:03
41  
+1 Its a horrible way to search for a simple string, but many visitors to SO are looking for any way to search for any of their own substrings, and it is helpful that the suggestion has been brought up. Even the OP might have oversimplified - let him know of his alternatives. – SamGoody Nov 9 '11 at 9:53
34  
Technically, the question asks how to find words not a substring. This actually helped me as I can use this with regex word boundries. Alternatives are always useful. – Lego Stormtroopr Aug 20 '13 at 5:57
10  
+1 for the answer and -1 to the @plutov.by comment because , strpos is just a single check meanwhile regexp you can check many words in the same time ex: preg_match(/are|you|not/) – albanx Nov 5 '14 at 17:05

Use strpos function:

if (strpos($a, 'are') !== false)
    echo 'true';
share|improve this answer

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;
}
share|improve this answer
55  
@RobinvanBaalen Actually, it can improves code readability. Also, downvotes are supposed to be for (very) bad answers, not for "neutral" ones. – Xaqq Jul 9 '13 at 8:56
19  
@RobinvanBaalen functions are nearly by definition for readability (to communicate the idea of what you're doing). Compare which is more readable: if ($email->contains("@") && $email->endsWith(".com)) { ... or if (strpos($email, "@") !== false && substr($email, -strlen(".com")) == ".com") { ... – Brandin Jul 25 '13 at 12:12
3  
@RobinvanBaalen in the end rules are meant to be broken. Otherwise people wouldn't come up with newer inventive ways of doing things :) . Plus have to admit I have trouble wrapping the mind around stuff like on martinfowler.com. Guess the right thing to do is to try things out yourself and find out what approaches are the most convenient. – James P. Aug 22 '13 at 1:43
5  
Another opinion: Having an utility function which you can easily wrap can help debugging. Also it loundens the cry for good optimizers which eliminate such overhead in production services. So all opinions have valid points. ;) – Tino Feb 20 '14 at 21:09
4  
Of course this is usefull. You should encourage this. What happens if in PHP 100 there is a new and faster way to find string locations ? Do you want to change all your places where you call strpos ? Or do you want to change only the contains within the function ?? – Cosmin Jun 17 '15 at 9:44

To determine whether a string contains another string you can use the PHP function strpos().

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

<?php

$haystack = 'how are you';
$needle = 'are';

if (strpos($haystack,$needle) !== false) {
    echo '$haystack contains $needle';
}

?>

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.

share|improve this answer
2  
quote source? maxi-pedia.com/string+contains+substring+PHP – btk Dec 19 '10 at 23:39
1  
+1 for == compare that will not work, you will need to do a === – Amol M Kulkarni Sep 4 '14 at 6:41

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).

share|improve this answer
11  
this should be the canonical answer. Because we're looking for words and not substrings, regex is appropriate. I'll also add that \b matches two things that \W doesn't, which makes it great for finding words in a string: It matches beginning of string (^) and end of string ($) – code_monk Oct 12 '14 at 2:09
    
This doesn't work: 3v4l.org/vPk2V – Jimbo Jun 23 '16 at 8:38
    
this should be the correct answer.. the rest of the answers will find "are" in a string like "do you care".. As mentioned by @Dtest – Robert Sinclair Jun 30 '16 at 7:17
    
@RobertSinclair Is that so bad? If you asked me if the string "do you care" contains the word "are" I would say "yes". The word "are" is clearly a substring of that string. That's a separate question from """Is "are" one of the words in the string "do you care"""". – Paulpro Jul 5 '16 at 19:15
    
@Paulpro Eventhough OP didn't specify the $a is a phrase, I'm pretty sure it was implied. So his question was how to detect the Word inside the Phrase. Not if a Word contains a Word inside of it, which I would assume would be irrelevant more often than not. – Robert Sinclair Jul 6 '16 at 22:08

Using strstr() or stristr() if your search should be case insensitive would be another option.

share|improve this answer
6  
A note on the php.net/manual/en/function.strstr.php page: Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead. – Jo Smo Feb 8 '14 at 17:49
    
@tastro Are there any reputable benchmarks on this? – Wayne Whitty Jun 17 '14 at 10:26

Look at strpos():

<?php
    $mystring = 'abc';
    $findme   = 'a';
    $pos = strpos($mystring, $findme);

    // Note our use of ===. Simply, == would not work as expected
    // because the position of 'a' was the 0th (first) character.
    if ($pos === false) {
        echo "The string '$findme' was not found in the string '$mystring'.";
    }
    else {
        echo "The string '$findme' was found in the string '$mystring',";
        echo " and exists at position $pos.";
    }
?>
share|improve this answer

Make use of case-insensitve matching using stripos():

if (stripos($string,$stringToSearch) !== false) {
    echo 'true';
}
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer
1  
strstr() returns FALSE if the needle was not found. So a strlen is not necessary. – Ayesh K Sep 11 '12 at 4:13
    
good job for case-insensitive with stristr() – raBne Aug 6 '15 at 17:23

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 sush as strpos(), preg_match(), strstr() or stristr()

  1. can't search for multiple words
  2. 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 fulltext 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 fro  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 '<pre>';
    print_r($match_results);
echo '</pre>';

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 '<pre>';
    print_r($match_results);
echo '</pre>';

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 '<pre>';
    print_r($match_results);
echo '</pre>';

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 sush 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. Stop word 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

share|improve this answer

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:

<?php

if (!function_exists('is_str_contain')) {
  function is_str_contain($string, $keyword)
  {
    if (empty($string) || empty($keyword)) return false;
    $keyword_first_char = $keyword[0];
    $keyword_length = strlen($keyword);
    $string_length = strlen($string);

    // case 1
    if ($string_length < $keyword_length) return false;

    // case 2
    if ($string_length == $keyword_length) {
      if ($string == $keyword) return true;
      else return false;
    }

    // case 3
    if ($keyword_length == 1) {
      for ($i = 0; $i < $string_length; $i++) {

        // Check if keyword's first char == string's first char
        if ($keyword_first_char == $string[$i]) {
          return true;
        }
      }
    }

    // case 4
    if ($keyword_length > 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 
share|improve this answer
12  
Could you please tell me why in the world you would use a function like this, when strpos is a perfectly viable solution?... – sg3s Sep 19 '13 at 14:05
3  
@sg3s: you are totally right, however, strpos also based on something like that, also, I didn't posted it for rep just for sharing a bit of knowledge – Jason OOO Sep 19 '13 at 19:33
    
last var_dump is false – Sunny May 17 '15 at 21:29
1  
@Sunny: it was typo: var_dump(is_str_contain("mystringss", "strings")); //true – Jason OOO May 18 '15 at 10:44

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.

share|improve this answer
if (preg_match('are', $a)) {
   echo 'true';
}
share|improve this answer
    
that's right. better use "preg_match()" – joan16v Oct 30 '13 at 16:10
1  
I am getting the following warning: WARNING preg_match(): Delimiter must not be alphanumeric or backslash – Pathros Aug 10 '16 at 17:06

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.

share|improve this answer
1  
you probably meant: $found = false at the beginning – slownage Mar 4 '15 at 12:36
    
your function may not work if the word is linked with comma, question mark or dot. e.g. "what you see is what you get." and you want to determine if "get" is in the sentence. Notice the full stop next to "get". In this case, your function returns false. it is recommended to use regular expression or substr(I think it uses regular expression anyway) to search/replace strings. – lightbringer Apr 15 '15 at 6:12
    
@lightbringer you could not be more wrong with your recommendation, what does it mean for you "it is recommended" ? there is no supreme person that recommends or aproves. It's about the use of regular expression engine in php that is a blackhole in the language itself, you may want to try putting a regex match in a loop and benchmark the results. – decebal Apr 16 '15 at 11:46
$a = 'how are you';
if (strpos($a,'are')) {
    echo 'true';
}
share|improve this answer
9  
What does that return if you look for 'how'? – andrewsi Oct 9 '12 at 16:22
3  
Careful! Try strpos($a,'are') === FALSE instead. @andrewsi is right, looking for 'how' would break it. – Joost Oct 9 '12 at 16:24
1  
@Joost Instead, check strpos($a,'are') === false. Same thing, but uppercase FALSE in PHP is a constant referencing the lowercase boolean false – Robin van Baalen Dec 18 '12 at 18:53

Another option to finding the occurrence of a word from a string using strstr() and stristr() is like the following:

<?php
    $a = 'How are you?';
    if (strstr($a,'are'))  // Case sensitive
        echo 'true';
    if (stristr($a,'are'))  // Case insensitive
        echo 'true';
?>
share|improve this answer
    
This is backwards. The i in stristr stands for insensitive. – Adam Merrifield Apr 1 '14 at 2:20

You should use case Insensitive format,so if the entered value is in small or caps it wont matter.

<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) { 

 /*If i EXCLUDE : !== false then if string is found at 0th location, 
   still it will say STRING NOT FOUND as it will return '0' and it      
   will goto else and will say NOT Found though it is found at 0th location.*/
    echo 'Contains word';
}else{
    echo "does NOT contain word";
}
?>

Here stripos finds needle in heystack without considering case (small/caps).

PHPCode Sample with output

share|improve this answer
    
don't work if $needle = "this"; => codepad.org/wUIKQ0A8 – Nolwennig Sep 9 '16 at 11:53

The short-hand version

$result = false!==strpos($a, 'are');
share|improve this answer
5  
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Bono Mar 13 '15 at 13:23

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';
}
share|improve this answer
3  
it will fail if $string is Are are, are? – Sunny May 17 '15 at 21:35

Maybe you could use something like this:

<?php
    findWord('Test all OK');

    function findWord($text) {
        if (strstr($text, 'ok')) {
            echo 'Found a word';
        }
        else
        {
            echo 'Did not find a word';
        }
    }
?>
share|improve this answer

You can use the strstr function:

$haystack = "I know programming";
$needle   = "know";
$flag = strstr($haystack, $needle);

if ($flag){

    echo "true";
}

Without using 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 ";
}
share|improve this answer
    
Crashes if you search the first word. – T30 Mar 21 '16 at 12:28

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';
}
share|improve this answer

It can be done in three different ways:

 $a = 'How are you?';

1- stristr()

 if (strlen(stristr($a,"are"))>0) {
    echo "true"; // are Found
 } 

2- strpos()

 if (strpos($a, "are") !== false) {
   echo "true"; // are Found
 }

3- preg_match()

 if( preg_match("are",$a) === 1) {
   echo "true"; // are Found
 }
share|improve this answer
    
good, but preg_match is risky since it can return false or 0. You should be testing for ===1 in #3 – Shapeshifter Dec 28 '15 at 4:10

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';
share|improve this answer

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.

share|improve this answer

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):

<?php

function contains_word($str, $word) {
  // split string into words
  // separators are substrings of at least one non-word character
  $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);

  // now the words can be examined each
  foreach ($arr as $value) {
    if ($value === $word) {
      return true;
    }
  }
  return false;
}

function test($str, $word) {
  if (contains_word($str, $word)) {
    echo "string '" . $str . "' contains word '" . $word . "'\n";
  } else {
    echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
  }
}

$a = 'How are you?';

test($a, 'are');
test($a, 'ar');
test($a, 'hare');

?>

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 (..)

share|improve this answer

In PHP, the best way to verify if a string contains a certain substring, is to use a simple helper function like this :

function contains($haystack, $needle, $caseSensitive = false) {
    return $caseSensitive ? 
            (strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
            (stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}

Explanation :

  • strpos finds the position of the first occurrence of a case-sensitive substring in a string
  • stripos finds the position of the first occurrence of a case-insensitive substring in a string
  • myFunction($haystack, $needle) === FALSE ? FALSE : TRUE ensures that myFunction always returns a boolean and fixes unexpected behavior when the index of the substring is 0
  • $caseSensitive ? A : B selects either strpos or stripos to do the work, depending on the value of $caseSensitive

Output :

var_dump(contains('bare','are'));            // Outputs : bool(true)
var_dump(contains('stare', 'are'));          // Outputs : bool(true)
var_dump(contains('stare', 'Are'));          // Outputs : bool(true)
var_dump(contains('stare', 'Are', true));    // Outputs : bool(false)
var_dump(contains('hair', 'are'));           // Outputs : bool(false)
var_dump(contains('aren\'t', 'are'));        // Outputs : bool(true)
var_dump(contains('Aren\'t', 'are'));        // Outputs : bool(true)
var_dump(contains('Aren\'t', 'are', true));  // Outputs : bool(false)
var_dump(contains('aren\'t', 'Are'));        // Outputs : bool(true)
var_dump(contains('aren\'t', 'Are', true));  // Outputs : bool(false)
var_dump(contains('broad', 'are'));          // Outputs : bool(false)
var_dump(contains('border', 'are'));         // Outputs : bool(false)
share|improve this answer

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;
}
share|improve this answer
1  
can be simplified to return strpos($str, $character) !== false – afarazit Aug 19 '16 at 16:57
    
what abt if string is "Do you care" then – Saurabh Chandra Patel Nov 16 '16 at 16:19

protected by Community Apr 28 '13 at 21:46

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.