Now with PHP 8 you can do this using str_contains:
if (str_contains('How are you', 'are')) {
echo 'true';
}
Please note: The str_contains
function will always return true if the $needle (the substring to search for in your string) is empty.
$haystack = 'Hello';
$needle = '';
if (str_contains($haystack, $needle)) {
echo "This returned true!";
} else {
echo "This returned false!";
}
Output: This returned true!
You should first make sure the $needle (your substring) is not empty.
$haystack = 'How are you?';
$needle = '';
if ($needle && str_contains($haystack, $needle)) {
echo "This returned true!";
} else {
echo "This returned false!";
}
Output: This returned false!
It's also worth noting that the new str_contains
function is case-sensitive.
$haystack = 'How are you?';
$needle = 'how';
if ($needle && str_contains($haystack, $needle)) {
echo "This returned true!";
} else {
echo "This returned false!";
}
Output: This returned false!
Before PHP 8
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
Note that the use of !== false
is deliberate (neither != false
nor === true
will return the desired result); strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
Center one and right/left align other flexbox element
How to store objects in HTML5 localStorage/sessionStorage
How do I modify the URL without reloading the page?
Why doesnt percentage height work in HTML/CSS?
How can I validate an email address in JavaScript?
How can I vertically center a div element for all browsers using CSS?
How can I horizontally center an element?
Get top n records for each group of grouped results
Connect Java to a MySQL database
Syntax error due to using a reserved word as a table or column name in MySQL