Skip to content

Instantly share code, notes, and snippets.

@elron
Created August 26, 2020 17:50
Show Gist options
  • Save elron/1142947cedeacc226a0fd1e0338b206d to your computer and use it in GitHub Desktop.
Save elron/1142947cedeacc226a0fd1e0338b206d to your computer and use it in GitHub Desktop.
PHP function to check if a string contains a specific word(s)
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