In PHP, the best way to verify if a string contains a certain substring, is to use a simple helper function like this:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
Explanation:
- strpos finds the position of the first occurrence of a case-sensitive substring in a string.
- stripos finds the position of the first occurrence of a case-insensitive substring in a string.
myFunction($haystack, $needle) === FALSE ? FALSE : TRUE
ensures that myFunction
always returns a boolean and fixes unexpected behavior when the index of the substring is 0.
$caseSensitive ? A : B
selects either strpos or stripos to do the work, depending on the value of $caseSensitive
.
Output:
var_dump(contains('bare','are')); // Outputs: bool(true)
var_dump(contains('stare', 'are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are', true)); // Outputs: bool(false)
var_dump(contains('hair', 'are')); // Outputs: bool(false)
var_dump(contains('aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are', true)); // Outputs: bool(false)
var_dump(contains('aren\'t', 'Are')); // Outputs: bool(true)
var_dump(contains('aren\'t', 'Are', true)); // Outputs: bool(false)
var_dump(contains('broad', 'are')); // Outputs: bool(false)
var_dump(contains('border', 'are')); // Outputs: bool(false)