【问题标题】:PHP: How to capitalize first letter of first word in a sentence, including a set of non-ASCII values?PHP:如何将句子中第一个单词的首字母大写,包括一组非 ASCII 值?
【发布时间】:2016-12-29 08:08:06
【问题描述】:

我在这里找到了答案:How to capitalize first letter of first word in a sentence? 但是,当句子以 "« 等字符开头时,它不起作用。

在上面链接中找到的代码是:

$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));

这是我需要的处理示例

$input  => «the first article title» 
$output => «The first article title»

$input  => « the first article title »
$output => « The first article title »

$input  => "être"
$output => "Étre"

这个想法是忽略任何非字母(不在 [a-z, A-Z] + 法语字符中)并应用于第一个字母,其余的将与输入保持相同。

【问题讨论】:

  • $input 的内容是什么?显示输入和预期输出
  • 使用输入 => 输出示例更新问题。不可能从 cmets 中理解你想要的。
  • ucfirst() 呢?

标签: php regex character-encoding


【解决方案1】:

应用限制,以便仅替换 1 个字符:

$output = preg_replace('/[a-z]/e', 'strtoupper("$0")', strtolower($input), 1);

虽然你现在应该使用preg_replace_callback() 而不是/e 开关:

$output = preg_replace_callback(
    '/[a-z]/',
    function($matches) { return strtoupper($matches[0]); },
    strtolower($string),
    1
);

编辑

在将问题更改为需要 UTF8 处理的范围蔓延之后:

$output = preg_replace_callback(
    '/\p{L}/u',
    function($matches) { return mb_strtoupper($matches[0]); },
    mb_strtolower($string),
    1
);

【讨论】:

  • 嗨,当它不是法语字符时它工作正常。例如“être”作为输入将输出“êTre”。
  • 你必须喜欢范围蠕变;您从未在原始问题中提及非 ASCII 字符
  • 嗨,它返回空字符串:-(
  • 我可以看到,我使用的是 php 5.3,这就是为什么不起作用。请,任何想法
猜你喜欢
  • 2011-07-20
  • 2014-07-11
  • 2023-04-04
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多