/ Published in: PHP

URL: http://www.maxi-pedia.com/string+contains+substring+PHP
how to know if a string contains another string
Expand |
Embed | Plain Text
Check for string inside a string Assumptions: Let's have one string called $haystack which holds the value of "mother". Then, we assume another string called $needle which holds the value of "other". What we are doing: We want the computer to tell us whether the $haystack mother includes the word other. How to check if PHP string contains another string Often, we see two approaches for this. One option is to use the strpos PHP function. The following example shows how this is used: <?php if($pos === false) { // string needle NOT found in haystack } else { // string needle found in haystack } ?> Watch out, checking for substring inside string in PHP can be tricky. Some people do just something like if ($pos > 0) {} or perhaps something like if (strpos($haystack,$needle)) { // We found a string inside string } and forget that the $needle string can be right at the beginning of the $haystack, at position zero. The if (strpos($haystack,$needle)) { } code does not produce the same result as the first set of code shown above and would fail if we were looking for example for "moth" in the word "mother". Php string contains substring Another option is to use the strstr() function. A code like the following could be used: if (strlen(strstr($haystack,$needle))>0) { // Needle Found } Note, the strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function. Which "find substring in a string" method is better? The strpos() function approach is a better way to find out whether a string contains substring PHP because it is much faster and less memory intensive. Any word of caution when checking for a substring inside string? If possible, it is a good idea to wrap both $haystack and $needle with the strtolower() function. This function converts your strings into lower case which helps to eliminate problems with case sensitivity.
Comments

You need to login to post a comment.
if you want a case insensitive search you can just call the eregi() function which will simply return a true/false boolean