Posted By

on 06/28/09


Tagged

php String contains


Versions (?)

if a string contains another string


 / Published in: PHP
 

URL: http://www.maxi-pedia.com/string+contains+substring+PHP

how to know if a string contains another string

  1. Check for string inside a string
  2.  
  3. Assumptions:
  4.  
  5. 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".
  6.  
  7. What we are doing:
  8.  
  9. We want the computer to tell us whether the $haystack mother includes the word other.
  10. How to check if PHP string contains another string
  11.  
  12. Often, we see two approaches for this. One option is to use the strpos PHP function. The following example shows how this is used:
  13.  
  14. <?php
  15. $pos = strpos($haystack,$needle);
  16.  
  17. if($pos === false) {
  18. // string needle NOT found in haystack
  19. }
  20. else {
  21. // string needle found in haystack
  22. }
  23. ?>
  24.  
  25. Watch out, checking for substring inside string in PHP can be tricky. Some people do just something like
  26.  
  27. if ($pos > 0) {}
  28.  
  29. or perhaps something like
  30.  
  31. if (strpos($haystack,$needle)) {
  32. // We found a string inside string
  33. }
  34.  
  35. and forget that the $needle string can be right at the beginning of the $haystack, at position zero. The
  36.  
  37. if (strpos($haystack,$needle)) { }
  38.  
  39. 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".
  40. Php string contains substring
  41.  
  42. Another option is to use the strstr() function. A code like the following could be used:
  43.  
  44. if (strlen(strstr($haystack,$needle))>0) {
  45. // Needle Found
  46. }
  47.  
  48. Note, the strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
  49. Which "find substring in a string" method is better?
  50.  
  51. 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.
  52. Any word of caution when checking for a substring inside string?
  53.  
  54. 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.

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: MMDeveloper on June 29, 2009

if you want a case insensitive search you can just call the eregi() function which will simply return a true/false boolean

You need to login to post a comment.