【发布时间】:2013-07-10 21:52:51
【问题描述】:
【问题讨论】:
-
php.net/manual/en/function.ucwords.php#58589。未内置您需要创建一个。
-
@Rikesh 太糟糕了。好吧,我想我不应该偷懒。
-
还不错,在非常特殊的情况下人们很少需要这样做。
【问题讨论】:
这是一个单行:
implode(' ', array_map(function($e) { return lcfirst($e); }, explode(' ', $words)))
示例:
function lcwords($words) {
return implode(' ', array_map(function($e) { return lcfirst($e); }, explode(' ', $words)));
}
$words = "First Second Third";
$lowercased_words = lcwords($words);
echo($lowercased_words);
【讨论】:
$string = "THIS IS SOME TEXT";
$string=explode(" ",$string);
$i=0;
while($i<count($string)){
$string[$i] = lcfirst($string[$i]);
$i++;
}
echo implode(" ",$string);
在this link 找到另一个函数。
【讨论】:
这可能对你有帮助
$str="hello";
$test=substr($str, 0,1);
$test2=substr($str, 1,strlen($str));
echo $test.strtoupper($test2);
【讨论】:
我不得不尝试使用正则表达式:
<?php
$pattern = "/(\b[a-zA-Z])(\w)/";
$string = "ThIs is A StriNG x y z!";
// This seems to work
$result = preg_replace_callback($pattern, function($matches) {
return (strtolower($matches[1]).$matches[2]);
}, $string);
echo $result;
echo "\r\n";
//This also seems to do the trick. Note that mb_ doesn't use /
echo mb_ereg_replace('(\b[a-zA-Z])(\w{0,})', "strtolower('\\1') . '\\2'", $string, 'e');
// I wanted this to work but it didn't produce the expected result:
echo preg_replace($pattern, strtolower("\$1") . "\$2", $string);
echo "\r\n";
【讨论】:
更短的单行:
implode(' ',array_map('lcfirst',explode(' ',$text)))
【讨论】:
function lcwords(string $str) :string
{
return preg_replace_callback('/(?<=^|\s)\w/', function (array $match) :string {
return strtolower($match[0]);
}, $str);
}
【讨论】:
我知道这个话题很古老,但问题仍然存在,这很遗憾(即使现在也没有lcwords())。
这里是lcwords(),用于将每个单词的每个首字母小写。
简单地说:这个解决方案是通用的,任何标点符号都不应该是它的问题。当然,你要为此付出代价:)
/**
* Lowercase the first character of each word in a string
*
* @param string $string The input string.
* @param string $delimiters The optional delimiters contains the word separator characters (regular expression)
*
* @return string Returns the modified string.
*/
function lcwords($string, $delimiters = "\W_\t\r\n\f\v") {
$string = preg_replace_callback("/([$delimiters])(\w)/", function($match) {
return $match[1].lcfirst($match[2]);
}, $string);
return lcfirst($string); // Uppercase first char if it's the beginning of the line
}
// Here is a couple of result examples:
echo lcwords("/SuperModule/ActionStyle/Controller.php").PHP_EOL;
// result: /superModule/actionStyle/controller.php
echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
// result: sEPARATED bY tABS aND sPACES
echo lcwords("HELLO").PHP_EOL;
// result: hELLO
echo lcwords("HEELO HOW-ARE_YOU").PHP_EOL;
// result: hEELO hOW-aRE_yOU
echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
// result: sEPARATED bY tABS aND sPACES
/([$delimiters])(\w)/ - 模式有两组:搜索 1 个非单词字符,后跟 1 个单词字符。然后单词字符将在回调中大写。所以只有选定的字符集得到更新 - 内容的最小变化。
【讨论】:
“小写字符串 php 中每个单词的第一个字符”,这是您得到的第一个响应:http://php.net/manual/en/function.lcfirst.php
【讨论】: