问题
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