Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.