Created
August 13, 2025 18:13
-
-
Save kpirnie/b6afd235efb2455a1249f681723d804a to your computer and use it in GitHub Desktop.
PHP - String Word Search
This file contains hidden or 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
| /** | |
| * string_contains_word | |
| * | |
| * PHP independant way to see if one string contains a specific word | |
| * | |
| * @since 7.4 | |
| * @access public | |
| * @static | |
| * @author Kevin Pirnie <[email protected]> | |
| * @package Kevin's Spam Cop | |
| * | |
| * @param string $_string The string to search | |
| * @param string $_word The string we're searching for | |
| * | |
| * @return string Returns a string containing the users referer | |
| * | |
| */ | |
| public static function string_contains_word( string $_string, string $_word ) : bool { | |
| // let's see if we have str_contains available to us | |
| if( function_exists( 'str_contains' ) ) { | |
| // we do, so use it | |
| return str_contains( $_string, $_word ); | |
| // mmm... nope | |
| } else { | |
| // guess we gotta go old school, but we want to match word for word, along with non-english characters | |
| return ( preg_match( '/(?<=[\s,.:;"\']|^)' . $_word . '(?=[\s,.:;"\']|$)/', $_string ) ); | |
| } | |
| // by default | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment