我已经在过去完成此操作,但不再具有我写的内容,并且不记得以前如何操作。在纠正了一些用户的输入,说“这是一个项目”到“这是一个项目”,我当然可以用当第一个字符是数字时更改为第一个大写字母
ucfirst(strtolower($text))
但它是没有用的,当$文字=“4个温度控制”
我敢肯定,我有这个分页,使‘4个温度控制’是输出,但找不到任何参考ucfirst跳过非字母字符
我已经在过去完成此操作,但不再具有我写的内容,并且不记得以前如何操作。在纠正了一些用户的输入,说“这是一个项目”到“这是一个项目”,我当然可以用当第一个字符是数字时更改为第一个大写字母
ucfirst(strtolower($text))
但它是没有用的,当$文字=“4个温度控制”
我敢肯定,我有这个分页,使‘4个温度控制’是输出,但找不到任何参考ucfirst跳过非字母字符
对于使用正则表达式:
$text = "4 temperature controls";
$result = preg_replace_callback('/^([^a-z]*)([a-z])/', function($m)
{
return $m[1].strtoupper($m[2]);
}, strtolower($text));
ucfirst()
根本就不是这里的用例,因为它无法预测你的后续字符,它总是与第一个字符一起工作。
试试这个:
<?php
$str = "4 temperature controls";
preg_match("~^(\d+)~", $str, $m);
$arr = explode($m[1],$str,2);
echo $m[1]." ".ucfirst(trim($arr[1]));
?>
的ucfirst()
函数用作资本返回一个字符串的第一个字符,你需要做的就是串$text
,使您只有字符转换为低,像这样什么... (然后你可以使用ucfirst()
之后)
$uppercase = $text;
$lowercase = strtolower(substr($uppercase, 2));
$text = $text[0] . " " . ucfirst($lowercase);
按照下面做一个ctype
测试注释将允许你检查FO R中的第一个字母出现,从而忽略所有前缀号码(上面的代码只会工作假设没有你的号码都在规模超过1个位数) ...
function textToLower($text) {
$textLength = strlen($text);
for ($i = 0; $i < $textLength; $i++) {
$char = $str[$i];
if (ctype_alpha($char)) {
$lowercase = strtolower(substr($text, $i));
$number = substr($text, 0, $i);
break;
}
}
$text = $number . ucfirst($lowercase);
return $text;
}
我也把它包在功能,使其更易于使用,作为一个例子,这会输出...
$input = "42 IS THE MEANING OF LIFE";
$output = textToLower($input); //(With the capitalised first letter)
echo $output; //Would be... "42 Is the meaning of life"
应该有一个ctype测试,它检查第一个字符是否是数字以便大写第一个文本发生 – 2014-09-05 07:57:42
@RoyalBg你是对的。我添加了一个新版本,用于检查字符串中的第一个字母出现位置,而不是假定该字符串只使用一个数字。 – Kolors 2014-09-05 09:42:07
有可能是一个更好的办法,但使用简单的preg_match
应该工作:
$text = "4 temperature controls";
$match = preg_match('/^([^a-zA-Z]*)(.*)$/', $text, $result);
$upper = ucfirst(mb_strtolower($result[2]));
echo $fixed = $result[1].$upper;
也许正则表达式或分割 – 2014-09-05 07:48:21