How to check if a string contains another string in PHP?

Introduction:
The strpos() function determines the position of the first occurrence of a substring within a string.

Example:

<?php
$haystack = "Hello, world!";
$needle = "world";

if (strpos($haystack, $needle) !== false) {
    echo "Found!";
} else {
    echo "Not found.";
}
?>

Explanation:

  • strpos($haystack, $needle) returns the position of $needle in $haystack.
  • The !== false check ensures that the substring exists in the string (even if at position 0).

Leave a Reply

Your email address will not be published. Required fields are marked *