2014-09-05 206 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; 
相关问题