Created
August 26, 2020 17:50
-
-
Save elron/1142947cedeacc226a0fd1e0338b206d to your computer and use it in GitHub Desktop.
PHP function to check if a string contains a specific word(s)
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
function contains($str, array $arr) { | |
// Works in Hebrew and any other unicode characters | |
// Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed | |
// Thanks https://www.phpliveregex.com/ | |
if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true; | |
} | |
// Works in English | |
contains('hello how are you', ['are']); // true | |
contains('hello how are you', ['hi', 'hola', 'hello']); // true | |
contains('hello how are you', ['llo']); // false | |
// Works in Hebrew and other unicode languages | |
contains( | |
'שלום מה נשמע', | |
['מה'] | |
); // true | |
contains( | |
'שלום מה נשמע', | |
['לו'] | |
); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment