filter words on a string in PHP

妖精的绣舞 提交于 2020-01-04 05:21:49

问题


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!


回答1:


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".




回答2:


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);



回答3:


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


来源:https://stackoverflow.com/questions/10854401/filter-words-on-a-string-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!