-1

我一直在寻找一种在 PHP 中转换字符串的方法,以便第一个字母变为大写,其余字母变为小写。

目前我正在做我认为是标准的方式:

ucfirst(strtolower($string));

但我发现一些编程语言(即 tcl)可以用一个指令来完成:

totitle

有没有办法在 PHP 中做到这一点?这不是问题,我只是一个古玩花花公子:D

谢谢

4

6 回答 6

0

您可以自己创建这样的功能。

不要忘记您应该mb_*对用户输入的数据使用函数。英语不是人们使用的唯一语言。看这个问题:ucfirst() function for multibyte character encodings

于 2014-01-31T16:19:44.063 回答
0

你应该这样走

<?php
$string= 'HELLO WORLD';
$string = strtolower($string);
$string = ucfirst($string);
?>
于 2014-01-31T16:21:31.110 回答
0
function totitle($string){
  return ucfirst(strtolower($string));
}

瞧 :)

于 2014-01-31T16:15:44.780 回答
0

“标题”大小写将字符串中的每个单词大写(即空格后面的每个字母)。您的方法会导致“乱世佳人”,而标题外壳会产生“乱世佳人”。

我不会担心:您所做的事情既简单又直观,如果它可以满足您的需求,那么没有任何内在函数可以做同样的事情。

于 2014-01-31T16:17:17.967 回答
0

有一个本地函数执行标题大小写并且是多字节安全的。这是一个非常整洁的解决方案,因为在将所有单词的前导字母变为大写之前,您无需将字符串全部准备为小写。

代码:(演示

$string = "OH HeLlo world, it'S \"NiCE\" 'to' sEe you!";
echo mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');

输出:

Oh Hello World, It's "Nice" 'To' See You!

以上表明https://www.php.net/manual/en/function.mb-convert-case.php#119629上的评论对于与双引号 wtapped 单词相关的行为是不正确的。


另外,在 Laravel 中,还有一个可以提到的辅助方法:title().

use Illuminate\Support\Str;

$converted = Str::of('a nice title uses the correct case')->title();

// A Nice Title Uses The Correct Case

来源:https ://laravel.com/docs/8.x/helpers#method-fluent-str-title

于 2021-08-12T13:46:12.103 回答
-1

如果您的字符串中有多个单词,ucwords()可以将每个单词的第一个字母转换为大写。

$string = 'hello world HELLO, wORlD HOW are You';
echo upperLowerCase($string);

function upperLowerCase($string) {
  return ucwords(strtolower($string));
}
于 2021-08-12T12:52:18.187 回答