2016-12-28 28 views
1

我在这里找到了答案:How to capitalize first letter of first word in a sentence?但是,当句子以"«等字符开头时,它不起作用。PHP:如何将一个句子中第一个单词的首字母大写,包括一组非ASCII值?

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

$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" 

的想法是忽略任何非字母(不即[az,AZ ] +法国字符)并适用于第一个字母,其余部分与输入保持一致。

+2

什么是'$ input'内容?显示输入和预期输出 – RomanPerekhrest

+0

使用输入=>输出示例更新问题。你不可能从评论中了解到你想要的。 – Dekel

+0

['ucfirst()'](http://php.net/manual/en/function.ucfirst.php)呢? – axiac

回答

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 
); 
+0

嗨,当它不是法国字符时它可以正常工作。例如,“être”作为输入将输出“êTre”。 – yazuk

+0

你必须爱范围蠕变;你从来没有提到原始问题中的非ASCII字符 –

+0

嗨,它返回空字符串:-( – yazuk

相关问题