Which function is used to find the substring of string in php?

Sometimes it requires to check a particular character or string exists in another string. PHP has many functions to check a string contains another substring. Some of these PHP functions are case-sensitive and some are case-insensitive. The uses of two types of functions have been explained in this tutorial with examples.

Pre-requisite:

The scripts used in the examples of this tutorial are written based on the PHP 8 version. Do the following task before executing the examples of this script.

  1. Install apache2 and PHP 8.
  2. Set execute permission for all files and folders under /var/www/html folder where all PHP files will be stored.

Use of strpos[] Function

The strpos[] function is used to find out the position of the first occurrence of the substring in the main string. The syntax of this function is given below.

strpos[string $main_string, string $search_string, [,int $offset]]:int | False

The first argument and the second argument of this function are mandatory arguments and the third argument is optional. The first argument takes the main string value and the second argument takes the search string value. The third argument takes the starting position of the argument. It returns the position value if the substring exists in the main string otherwise returns False.

Example-1: Search substring using strpos[] function

Create a PHP file with the following script to search a substring in a string from the starting of the string and the particular position of the string. Here, the search string or substring and the starting position to start searching will be given the URL. The $_GET[] array has been used to read the value of the URL query parameters named ‘search’ and ‘pos’.

Bài mới nhất

Chủ Đề