strpos – Find the Position of a String

Finding the position of a string or substring can be made with this php functions:

  • strpos($string, $seached_string [,$offset]) – returns position of the first occurrence of $searched_string inside $string or FALSE if $searched_string is not found. If $offset is specified, the seach will be made starting with $offset position.
  • stripos($string, $seached_string [,$offset]) – idem, but the search is case-insensitive
  • strrpos($string, $seached_string [,$offset]) – returns the position of the last occurrence of $searched_string inside $string, or FALSE
  • strripos($string, $seached_string [,$offset]) – idem with strrpos but is case-insensitive


Finding the position of a substring in string examples

  1. <?php
  2. $string = "Count of Monte Cristo";
  3. echo strpos($string, "nt"); // 3 (first occurrence of nt inside $string)
  4. echo strrpos($string, "nt"); // 11 (last occurrence of nt)
  5. echo strpos($string, "nt", 4); // 11 (first occurrence of nt after 4-th position)
  6. var_dump(strpos($string, "count")); // FALSE, because strpos() is case-sensitive
  7. echo stripos($string, "Count"); //0
  8. ?>

Be careful when you verify the result of those php functions! When the searched string is at the begining of the string in which we are searching, the strpos() function returns 0, which is == FALSE; so if we use the == operator there is the risk to get wrong conclusions:

  1. <?php
  2. $string = "Count of Monte Cristo";
  3. if(strpos($string, "Co") == false) { // "Co" is at position 0, which == false!
  4.       echo "It hasn't been found"; // this line will execute!
  5. }
  6. ?>

No related php tutorials.

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark
tabs-top

Leave a Reply