Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Last active January 21, 2019 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronjonesweb/a0a5d323b75702bd50c29e766ade2881 to your computer and use it in GitHub Desktop.
Save cameronjonesweb/a0a5d323b75702bd50c29e766ade2881 to your computer and use it in GitHub Desktop.
Accurately check if a string contains a phrase
<?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.
}
<?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