+4 votes
in Programming Languages by (40.5k points)
I want to check whether a substring is present in a given string. Which PHP function should I use for it?

E.g.

substring = "hello"

string = "hello world"

The function should find this substring in the string.

1 Answer

+3 votes
by (349k points)
selected by
 
Best answer

You can use the strpos() function to find if a substring is present in a string. The function finds the position of the first occurrence of a substring inside a string.

The syntax of the function is:

strpos(string, substring, start)

Where,

string= the string to search,

substring=the substring to find,

start= where to begin the search. If the start is a negative number, it counts from the end of the string.

Here is an example to show how to use this function. If the substring is not present in the string, it will return FALSE. So, I am checking the function's return value to determine the presence of the substring.

<?php
$main_str = "Hello, how are you?";
$test_str1 = "are";

if (strpos($main_str,$test_str1)!== FALSE){
    print("substring found\n");
}else{
    print("substring not found\n");
}
?>


...