How to find the position of the first occurrence of a substring in a string in php?

In PHP, the iconv_strpos() function is used to read the first character from a given string. It finds the position of the first occurrence of a character in a string. It is an inbuilt function in PHP.

1. Code:

<?php
   # UTF-8 string
   $int = iconv_strpos("Soltuts.com is providing PHP tutorials, tips, tricks and code snippets.", "com",0, "UTF-8");
   
   // It will returns the number of characte
   var_dump($int);
?>

2. Example:

Input:

string : Soltuts.com is providing PHP tutorials, tips, tricks and code snippets.
substring: com 

Output:

output: int(8)

3. Syntax:

string iconv_strpos(string $haystack, string $needle, int $offset, string $encoding)

Parameters:

iconv_strpos() function accepts four different parameters− $haystack, $needle, $offset and $encoding.

  • $haystack− It denotes the whole string.
  • $needle− The $needle parameter is used to search the substring from the given whole string.
  • $offset− The $offset parameter is optional it is used to specify the position from which the search should be performed. If the offset is negative then it will count from the end of the string.
  • $encoding− if the $encoding parameter is absent or null, then the string will assume that it may be encoded in iconv.internal_encoding.

Return Values:

The iconv_strpos() function returns the numeric position of the first occurrence of the needle in the haystack. If the needle is not found, then the function will return False.

Note: From PHP 8.0 version, encoding is nullable and from PHP 7.1, iconv_strpos() function support for the negative offsets has been added.