PHP – Check if substring exists in string

In this post we will be creating a PHP script that will check if a substring is present within an existing string, to do this we will be using the ‘str_contains()’ function which determines if a string contains a given substring.

See below our string and substring for this example.

$string = "hello how are you";
$substring = "hello";

In the snippet of code below we use the ‘str_contains()’ to check if the substring exists within the string.

<?php
	$string = "hello how are you";
	$substring = "Aloha";
	
    if (str_contains($string, $substring)) { 
		echo 'Substring Exists';
	}
	
	else{
		echo 'Substring Doesnt Exist';
	}
	
?>

The above would return the following as output.

Leave a Reply