I want to find and replace some words. the problem is i do not want to replace the words if they are in a word. forexample this is the sentence: I want to change. PHP: the output should be: I want change. PHP: as you see "an" did not changed in the word "change" because "an" is not by it self. $short = array('of', 'to', 'in', 'an'); $title = str_replace($short, "", $title); PHP: How can i do this? Thanks
Use preg_replace instead of str_replace so that you can utilize the word-boundry character. $short = array('of', 'to', 'in', 'an'); $pattern = '#\b' . implode('\b|\b', $short) . '\b#i'; $title = preg_replace($pattern, '', $title); Code (markup):
<?php $subject='I want an anaconda'; $search=' an ';//observe the leading and traliing whitespaces around 'an' $replace=' ';//replace it with a white-space $subject=str_replace($search,$replace,$subject); echo $subject;//I want anaconda //you may have a $search array to look for other possible situations where you may have that word. ?> PHP:
Which completely falls apart with Seriously, don't fumble around with str_replace, let the computer do the work for you and use preg_replace.
^^ That is why you must read the solution completely and understand it. You missed the comment that read And if case is a issue. use case-insensitive replacements, str_ireplace() !