Last active
January 21, 2019 05:35
-
-
Save cameronjonesweb/a0a5d323b75702bd50c29e766ade2881 to your computer and use it in GitHub Desktop.
Accurately check if a string contains a phrase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$string = 'Hello world!'; | |
$phrase = 'He'; | |
if ( strpos( $string, $phrase ) ) { | |
// This code won't run. | |
} | |
if ( cameronjonesweb_string_contains_phrase( $string, $phrase ) ) { | |
// This code will run. | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Searches for a phrase in a given string | |
* | |
* @param string $haystack The haystack to search. | |
* @param string $needle The needle to search for. | |
* @return bool Whether the needle was found or not | |
*/ | |
function cameronjonesweb_string_contains_phrase( $haystack, $needle ) { | |
// As strpos will return 0 if the string begins with the phrase, we need to do an is_numeric check | |
return is_numeric( strpos( $haystack, $needle ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment