正如标题所示,我正在尝试检测字符串的大小写,并将相同的格式应用于新字符串。
示例:
Yellow cheese >>>检测到它只是第一个大写的字符>>>将blue cheese更改为Blue cheese。
这个是可能的吗?
发布于 2011-03-16 21:05:48
您可以尝试:
$ref = 'Yellow cheese';
$str = 'blue cheese';
$ref_words = explode(' ', $ref);
$str_words = explode(' ', $str);
for($i=0; $i<count($ref_words); $i++) {
if (preg_match('/^[A-Z]/', $ref_words[$i])) {
$str_words[$i] = ucfirst($str_words[$i]);
}
}
$res = implode(' ', $str_words);
echo $res,"\n";输出:
Blue cheese发布于 2011-03-16 20:59:21
这在某种程度上取决于你需要的算法有多聪明。一个简单的例子可以是这样的:
<?php
$v1 = "Yellow cheese";
$v2 = "blue cheese";
$out = "";
for($i = 0; $i < max(strlen($v1), strlen($v2)); $i++) {
if($v1[i] === strtoupper($v1[i])) {
$out .= strtoupper($v2[i]);
} else {
$out .= strtolower($v2[i]);
}
}这将是非常盲目的,所以
YelLoW ChEEse
> BluE CHEsSEhttps://stackoverflow.com/questions/5325488
复制相似问题