第一个字符大写并忽略 php 中的少数特殊字符

First character upper case and ignore few special characters in php

我正在尝试将大写文本显示为短语中第一个大写的字符。如果有任何特殊字符,则必须忽略它们。

例如:

SECTION 1: IDENTIFICATION OF THE SUBSTANCE/PREPARATION AND OF THE COMPANY/UNDERTAKING

上面是我的文字,我希望上面的文字显示得像

Section 1: Identification of the substance/preparation and of the company/undertaking

截至目前,我尝试了 echo ucfirst(strtolower($word));

输出

Section 1: identification of the substance/preparation and of the company/undertaking

我怎样才能做到这一点? 谢谢

您可以分成两部分:

$exploded = explode(': ', $phrase);

然后ucfirst各部分:

$exploded[0] = ucfirst($exploded[0]);
$exploded[1] = ucfirst(strtolower($exploded[1]));

你终于可以加入所有人了:

echo join(': ', $exploded);

$phrase = 'SECTION 1: CIAO MONDO';
$exploded = explode(': ', $phrase);
$exploded[0] = ucfirst($exploded[0]);
$exploded[1] = ucfirst(strtolower($exploded[1]));
echo join(': ', $exploded); // Section 1: Ciao mondo

您可以 split 使用 : 包围可选的间隔,并在每个拆分项目上调用 ucfirst 然后将它们连接在一起:

$out="";

foreach (preg_split('/(\h*[:.]\h*)/', strtolower($str), 0, PREG_SPLIT_DELIM_CAPTURE) as $s)
   $out .= ucfirst($s)

echo "$out\n";

//=> Section 1: Identification of the substance/preparation and of the company/undertaking

\h*[:.]\h*:. 上拆分,两边可选间隔。您可以在此处添加更多要拆分的字符 class。