If you want to search for a “word” (string) within text (string) you have ready built-in functions in PHP. But with my function you will make them a little easier to use.
So the built-in function for PHP 8+ is str_contains and for PHP before version 8 – strpos, with strpos a lot more difficult to use.
Here is a function that will use these built-in functions but in an easier way. It returns true if the string contains your search word, and false if it doesn’t. This way you can use it in your IF statements easy.
function contains($piece, $string, $case_sensitive = false) {
if (PHP_MAJOR_VERSION >= 8) {
if (!$case_sensitive) {
return (str_contains(strtolower($string), strtolower($piece))) ? true : false;
} else {
return (str_contains($string, $piece)) ? true : false;
}
} else {
if (!$case_sensitive) {
return (strpos(strtolower($string), strtolower($piece)) !== false) ? true : false;
} else {
return (strpos($string, $piece) !== false) ? true : false;
}
}
}
It also has a mode – case sensitive comparison or not.
Here is how it works.
If i want to do a case insensitive search (default), i just provide 2 parameters – the word (string) i want to search for and the whole string
var_dump((contains('expect-ct', 'Expect-CT: qwoeqwoekqwokeo')));
This will evaluate to true, because it’s case insensitive.
If i want to do a case sensitive search:
var_dump((contains('expect-ct', 'Expect-CT: qwoeqwoekqwokeo', true)));
This will evalute to false
Here is a full example if usage
function contains($piece, $string, $case_sensitive = false) {
if (PHP_MAJOR_VERSION >= 8) {
if (!$case_sensitive) {
return (str_contains(strtolower($string), strtolower($piece))) ? true : false;
} else {
return (str_contains($string, $piece)) ? true : false;
}
} else {
if (!$case_sensitive) {
return (strpos(strtolower($string), strtolower($piece)) !== false) ? true : false;
} else {
return (strpos($string, $piece) !== false) ? true : false;
}
}
}
$text = 'I want freedom in the pursuit for happiness';
$search_for_word = 'Happiness';
if (contains($search_for_word, $text)) {
echo "Word found";
// Do something else, like a logic
} else {
echo "Word not found";
// Do some other logic
}
Enjoy!
For more PHP code examples – check out the PHP category