简体   繁体   中英

filter words on a string in PHP

I have a string in which all of the beginning of every word are capitalized. Now i want to filter it like if it can detect words link "as, the, of, in, etc" it will be converted to lower cases. I have a code that replace and convert it to lower case, but for 1 word only like below:

$str = "This Is A Sample String Of Hello World";
$str = preg_replace('/\bOf\b/', 'of', $str);

output: This Is A Sample String of Hello World

So what i want is that to filter other words such as on the string like "is, a". Its odd to repeat the preg_replace for every word to filter.

Thanks!

Use preg_replace_callback() :

$str = "This Is A Sample String Of Hello World";
$str = ucfirst(preg_replace_callback(
       '/\b(Of|Is|A)\b/',
       create_function(
           '$matches',
           'return strtolower($matches[0]);'
       ),
       $str
   ));
echo $str;

Displays "This is a Sample String of Hello World".

Since you know the exact word and format you should be using str_replace rather than preg_replace; it's much faster.

$text = str_replace(array('Is','Of','A'),array('is','of','a'),$text);

Try this:

$words = array('Of', 'Is', 'A', 'The');  // Add more words here

echo preg_replace_callback('/\b('.implode('|', $words).')\b/', function($m) {
    return strtolower($m[0]);
}, $str);


// This is a Sample String of Hello World

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM