PHP-每个单词的首字母大写期望某些单词 [英] PHP - Capitalise first character of each word expect certain words
问题描述
我有一堆这样的字符串:
I have a batch of strings like so:
tHe iPad hAS gONE ouT of STOCK
PoWER uP YOur iPhone
wHAT moDEL is YOUR aPPLE iPHOne
我要大写每个单词的第一个字符其余字符均小写- iPhone
或 iPad
的引用除外。如:
I want to capitalise the first character of each word and have the remaining characters lowercase - except any references of iPhone
or iPad
. As in:
通过使用:
ucwords(strtolower($string));
这可以满足大部分需要,但显然也可以在 iPad上完成
和 iPhone
:
This can do most of what is needed but obviously also does it on iPad
and iPhone
:
The Ipad Has Gone Out Of Stock
Power Up Your Iphone
What Model Is Your Apple Iphone
如何实现以下目标:
The iPad Has Gone Out Of Stock
Power Up Your iPhone
What Model Is Your Apple iPhone
推荐答案
为此 str_replace 。如果对前两个参数使用数组,则可以定义一组单词和替换:
You can use str_replace for this. If you use arrays for the first two arguments, you can define a set of words and replacements:
echo str_replace(['Ipad', 'Iphone'], ['iPad', 'iPhone'], ucwords(strtolower($string)));
来自文档:
如果搜索和替换是数组,则str_replace()从每个数组中获取一个值,并使用它们对主题进行搜索和替换。
If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.
这篇关于PHP-每个单词的首字母大写期望某些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!