我想在php中CaPiTaLiZe $string,不要问为什么:D
我做了一些研究,在这里找到了很好的答案,他们真的对我有帮助。但是,在我的例子中,我想要开始大写每个奇数字符(1,2,3...)在每一个字里。
例如,使用我的自定义函数,我得到的结果是"TeSt ExAmPlE“,而我想得到的是"TeSt example”。在第二个例子中,单词" example“以大写"E”开头?
那么,有没有人能帮我?:)
发布于 2011-08-23 05:42:40
这里有一个应该可以工作的one liner。
preg_replace('/(\w)(.)?/e', "strtoupper('$1').strtolower('$2')", 'test example');http://codepad.org/9LC3SzjC
发布于 2011-08-23 05:28:48
我会把它变成一个数组,然后再把它放回原处。
<?php
$str = "test example";
$str_implode = str_split($str);
$caps = true;
foreach($str_implode as $key=>$letter){
if($caps){
$out = strtoupper($letter);
if($out <> " ") //not a space character
$caps = false;
}
else{
$out = strtolower($letter);
$caps = true;
}
$str_implode[$key] = $out;
}
$str = implode('',$str_implode);
echo $str;
?>演示:http://codepad.org/j8uXM97o
发布于 2011-08-23 05:42:58
我会使用正则表达式来做这件事,因为它很简洁和容易做:
$str = 'I made some research and found good answers here, they really helped me.';
$str = preg_replace_callback('/(\w)(.?)/', 'altcase', $str);
echo $str;
function altcase($m){
return strtoupper($m[1]).$m[2];
}输出:"I MaDe SoMe ReSeArCh AnD FoUnD GoOd AnSwErS HeRe,ThEy ReAlLy HeLpEd Me.“
Example
https://stackoverflow.com/questions/7153801
复制相似问题