我有以下段落:
This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.
我想在每个换行符中将第一个字符转换为uppercase
。
因此段落应如下所示:
This is the first line.
This is the second line.
We live in Europe.
This is the fourth line.
到目前为止,我可以将第一个字符转换为大写字母,但它会使用ucfirst()
和ucword()
echo ucfirst($str);
有没有办法使用ucfirst()
或preg_replace()
函数来解决这个问题?
谢谢!
答案 0 :(得分:5)
这个怎么样?
$a = "This is the first line.\n\r
this is the second line.\n\r
we live in Europe.\n\r
this is the fourth line.";
$a = implode("\n", array_map("ucfirst", explode("\n", $a)));
答案 1 :(得分:3)
你可以使用它。
<?php
$str = strtolower('This is the first line.
This is the second line.
We live in Europe.
This is the fourth line.');
$str = preg_replace_callback('~^\s*([a-z])~im', function($matches) { return strtoupper($matches[1]); }, $str);
echo $str;
输出:
This is the first line.
This is the second line.
We live in europe.
This is the fourth line.
i
修饰符表示我们不关心这种情况,m
表示字符串的每一行都是^
的新行。这将大写一行的第一个字母,假设它以a-z开头。
答案 2 :(得分:1)
另一种方法是:
<?php
function foo($paragraph){
$parts = explode("\n", $paragraph);
foreach ($parts as $key => $line) {
$line[0] = strtoupper($line[0]);
$parts[$key] = $line;
}
return implode("\n", $parts);
}
$paragraph = "This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.";
echo foo($paragraph);
?>
答案 3 :(得分:1)
用大写字母替换每行的第一个下套管字符:
$str = preg_replace_callback(
'/^\s*([a-z])/m',
function($match) {
return strtoupper($match[1]);
},
$str);