2014-09-05 215 views
0

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

ucfirst(strtolower($text)) 

但它是沒有用的,當$文字=「4個溫度控制」

我敢肯定,我有這個分頁,使‘4個溫度控制’是輸出,但找不到任何參考ucfirst跳過非字母字符

+0

也許正則表達式或分割 – 2014-09-05 07:48:21

回答

2

對於使用正則表達式:

$text = "4 temperature controls"; 
$result = preg_replace_callback('/^([^a-z]*)([a-z])/', function($m) 
{ 
    return $m[1].strtoupper($m[2]); 
}, strtolower($text)); 

ucfirst()根本就不是這裏的用例,因爲它無法預測你的後續字符,它總是與第一個字符一起工作。

+0

試一下:'$ text =「php:一種編程語言」;'。它將小寫'A'。 – hek2mgl 2014-09-05 08:00:01

+0

@ hek2mgl這是OP的意圖,因爲我看到 – 2014-09-05 08:01:07

+0

可能這會處理輸入字符串更*仔細*:http://3v4l.org/iVm5J。它也不需要使整個琴絃變得更加亮麗。 (但可能不需要,只是一個提示) – hek2mgl 2014-09-05 08:07:58

0

試試這個:

<?php 
$str = "4 temperature controls"; 
preg_match("~^(\d+)~", $str, $m); 
$arr = explode($m[1],$str,2); 
echo $m[1]." ".ucfirst(trim($arr[1])); 

?> 
0

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" 
+0

應該有一個ctype測試,它檢查第一個字符是否是數字以便大寫第一個文本發生 – 2014-09-05 07:57:42

+0

@RoyalBg你是對的。我添加了一個新版本,用於檢查字符串中的第一個字母出現位置,而不是假定該字符串只使用一個數字。 – Kolors 2014-09-05 09:42:07

0

有可能是一個更好的辦法,但使用簡單的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; 
相關問題