Categories
PHP

Find positions of a substring in a string

How to find the position of the first or last occurrence of a substring in a string. You’ll also learn how to find the all positions of a substring in a string (or a multibyte string).

When looking for substrings in strings, the following functions are used:

  1. strpos finds the first occurrence of substring and returns its position.
    Find all occurrences of a substring.
  2. stripos works same as strpos but it ignores the case.
  3. strrpos finds the last occurrence of substring and returns its position.
  4. strripos works same as strrpos but it ignores the case.
  5. Find the position of a string in a multibyte string.

strpos()

<?php
 //Syntax
 strpos(string $haystack, string $needle, int $offset = 0): int|false

This function returns the index of the first occurrence of the substring, or false otherwise.

<?php
 $string    = 'Hello World';
 $substring = 'H';
 $pos = strpos($string, $substring);
 
/*Incorrect comparison
 if ($pos == false)
Use === or !== comparison operators*/
 if ($pos === false)
  echo "$substring not found";
 else
  echo "$substring index is $pos";
 //Prints: H index is 0

The use of == or != operator is incorrect because if string $string happens to start with $substring, strpos() returns 0, which evaluates to false. Therefore, a comparison using === or !== must be used to take the data type into account.

When called with two arguments, the search for the $substring needle is from the start of the haystack $string at position zero. When called with three arguments, the search occurs from the index $offset into the haystack $string. The following examples show how offset works:

<?php
 $string    = 'Hello World';
 $substring = 'o';
 echo strpos($string, $substring);    //4
 echo strpos($string, $substring, 5); //7

Example: Find multiple characters

The strpos( ) function can search for multiple characters and returns the index position of the first character. The following examples show how it works:

<?php
 //      01234567890
 $str = 'PHP, MySQL, JavaScript, Lamp';
 $sub = 'MySQL';
 $pos = strpos($str, $sub);
 echo "$sub index is $pos";
 //Prints: MySQL index is 5 

Example: Find all substring occurrences (positions) in the string.

If you need to count the number of times a substring occurs in a string use the substr_count() function. But if you want to determine all substring positions in the string, use a loop with strpos() function. See the following example:

<?php
 $str = 'Hello World';
 $sub = 'o';
 $ofs = 0; //offset
 echo substr_count($str, $sub);//2

 while (($pos = strpos($str, $sub, $ofs)) !== false)
 {
  echo $sub .' found at index '. $pos;
  echo '<br>';
  $ofs = $pos+1;
 }
 /*Prints:
 o found at index 4
 o found at index 7*/

stripos()

<?php
 //Syntax
 stripos(string $haystack, string $needle, int $offset = 0): int|false

The stripos() function works same as strpos() function, except it is case insensitive.

<?php
 $str = 'PHP, MySQL, JavaScript, PHP';
 $sub = 'php';
 $pos = stripos($str, $sub);
  
 if ($pos !== false)
  echo "$sub found at index $pos";
  //Prints: php found at index 0
  
 /*var_dump(
   strpos($str, $sub)
  );
 //bool(false)*/

strrpos()

<?php
 //Syntax
 strrpos(string $haystack, string $needle, int $offset = 0): int|false

This function searches from the end of the string. It returns the index of the last occurrence of the substring, or false otherwise.

Example: Find last occurrence of string

<?php
 $str = 'PHP, MySQL, JavaScript, PHP';
 $sub = 'PHP';
 $pos = strrpos($str, $sub); //24
 //echo strpos($str, $sub);  //0
 
 if ($pos !== false)
  echo "$sub found at index $pos";
  //Prints: PHP found at index 24

strripos()

<?php
 //Syntax
 strripos(string $haystack, string $needle, int $offset = 0): int|false

The strripos() function works same as strrpos() function, except it is case insensitive. This function finds the position of the last occurrence of a case-insensitive substring in a string.

<?php
 $str = 'PHP, MySQL, JavaScript, PHP';
 $sub = 'php';
 $pos = strripos($str, $sub);
  
 if ($pos !== false)
  echo "$sub found at index $pos";
  //Prints: php found at index 24
  
 /*var_dump(
   strrpos($str, $sub)
  );
 //bool(false)*/

Find the position of a string in a multibyte string

<?php
 //Syntax
 mb_strpos(
  string $haystack, string $needle,
  int $offset = 0,  ?string $encoding = null
  ): int|false

Use the following functions if you are dealing with multibyte strings, these functions accept an additional parameter $encoding for the character encoding. If the $encoding parameter is omitted or null, the internal character encoding will be used.

  1. mb_strpos() works same as strpos().
  2. mb_strrpos() works same as strrpos().
  3. mb_stripos() works same as stripos().
  4. mb_strripos() works same as strripos().

The multi-byte safe functions work based on the number of characters in a string. The first character’s position is 0, the second character’s position is 1, and so on.

<?php
 $str = 'ПХП, ЈаваСцрипт, ПХП';

 //Using named argument 'encoding'
 echo mb_strpos($str, 'ПХП', encoding:'UTF-8'); //0

 //Setting character encoding in 4th parameter
 echo mb_strpos($str, 'ПХП', 3, 'UTF-8'); //17

 //Omitting encoding parameter
  echo mb_strpos($str, 'ПХП', 3); //17

Example: Using mb_stripos, mb_strrpos, and mb_strripos

<?php
 $str = 'ПХП, ЈаваСцрипт, ПХП';
 
 echo mb_strrpos($str, 'ПХП')."\n";    //17
 echo mb_strrpos($str, 'ПХП', -4)."\n"; //0
 
 echo mb_stripos($str, 'пхп')."\n";    //0
 echo mb_stripos($str, 'пхп', 3)."\n"; //17
 
 echo mb_strripos($str, 'пхп')."\n";    //17
 echo mb_strripos($str, 'пхп', -4)."\n"; //0
 
 $pos = mb_strpos($str, 'пап');
 if ($pos === false)
  echo 'пап not found';
 else
  echo "пап found at position $pos";
 //пап not found

Manipulating substrings: