我已經在過去完成此操作,但不再具有我寫的內容,並且不記得以前如何操作。在糾正了一些用戶的輸入,說「這是一個項目」到「這是一個項目」,我當然可以用當第一個字符是數字時更改爲第一個大寫字母
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