31、PHP 原生魅力 - 字符串 - 大小写转换

作者: 温新

图书: 【原生 PHP 魅力】

阅读: 201

时间: 2024-11-21 16:01:28

你可以使用 mb_convert_case() 函数来转换句子的大小写。

该函数提供多种模式来影响你想要改变大小写的方式,其中一些模式非常相似:

$modes = [
    MB_CASE_UPPER,
    MB_CASE_LOWER,
    MB_CASE_TITLE,
    MB_CASE_FOLD,
    MB_CASE_UPPER_SIMPLE,
    MB_CASE_LOWER_SIMPLE,
    MB_CASE_TITLE_SIMPLE,
    MB_CASE_FOLD_SIMPLE
];

例如,你可以使用 MB_CASE_UPPER 将所有字符转换为大写,或者使用 MB_CASE_LOWER 将所有字符转换为小写,或者你可以得到首字母大写其余字母小写的单词,就像这样:“Hello, How Are You?”

<?php

$modes = [
    MB_CASE_UPPER,
    MB_CASE_LOWER,
    MB_CASE_TITLE,
    MB_CASE_FOLD,
    MB_CASE_UPPER_SIMPLE,
    MB_CASE_LOWER_SIMPLE,
    MB_CASE_TITLE_SIMPLE,
    MB_CASE_FOLD_SIMPLE
];

$str = 'Hello, HOW are yOu?';

foreach ($modes as $mode) {
    echo mb_convert_case($str, $mode) . PHP_EOL;
}

输出如下:

$ php 31-mbconvertcase.php
HELLO, HOW ARE YOU?
hello, how are you?
Hello, How Are You?
hello, how are you?
HELLO, HOW ARE YOU?
hello, how are you?
Hello, How Are You?
hello, how are you?
请登录后再评论