Example for PHP 7 (Using strpos())
In PHP 7, strpos() is commonly used to find the position of a substring within a string. $string = "Hello, welcome to Coding Dynasty!"; $substring = "welcome"; if (strpos($string, $substring) !== false) { echo "Substring found!"; } else { echo "Substring not found!"; }
In the above example, strpos() returns the position of the first occurrence of the substring or false if not found.
Example for PHP 8 (Using str_contains())
PHP 8 introduces a new function, str_contains(), which provides a simpler and more readable way to check if a string contains a substring. $string = "Hello, welcome to Coding Dynasty!"; $substring = "welcome"; if (str_contains($string, $substring)) { echo "Substring found!"; } else { echo "Substring not found!"; }
str_contains() returns true if the substring is found and false otherwise, making it more intuitive than strpos().
Conclusion
While strpos() is still available in PHP 8, the new str_contains() function offers a more readable solution. Both methods efficiently allow you to search for a substring within a string, with str_contains() being the preferred choice in PHP 8.