Add a word when only one word, not a compound word

I have the following function, I want it to remove "alpha" when only one word is not an integral part of a word like alphadog. Now, instead, I just see a β€œdog,” and that's not good. Any help?

function stripwords($string) { // build pattern once static $pattern = null; if ($pattern === null) { // pull words to remove from somewhere $words = array('alpha', 'beta', '-'); // escape special characters foreach ($words as &$word) { $word = preg_quote($word, '#'); } // combine to regex $pattern = '#\b(' . join('|', $words) . ')\b\s*#iS'; } $print = preg_replace($pattern, '', $string); list($firstpart)=explode('+', $print); return $firstpart; } 

edit: hi, I have another problem ... I edited above with a new version of the function: it breaks the words, adjusts the spaces, and then does something else that I need, but it does not remove the dash (or minus) .. . what's wrong? I tried something but to no avail ... thanks

+1
source share
2 answers

It:

 $pattern = '#' . join('|', $words) . '#iS'; 

Must be:

 $pattern = '#\b' . join('\b|\b', $words) . '\b#iS'; 
0
source

Use this regex pattern

/\balpha\b/

\b means "word boundary", it means that it will correspond to a separate word (if the word is surrounded by word delimiters).

Hope this helps

+4
source

Source: https://habr.com/ru/post/1399976/


All Articles