在php中,将每个换行符中的第一个字符转换为大写

在php中,将每个换行符中的第一个字符转换为大写,php,Php,我有以下一段: This is the first line. this is the second line. we live in Europe. this is the fourth line. 我想在每个换行符中将第一个字符转换为大写 所以这一段应该是这样的: This is the first line. This is the second line. We live in Europe. This is the fourth line. 到目前为止,我能够将第一个字符转换为大写

我有以下一段:

This is the first line.
this is the second line.
we live in Europe.
this is the fourth line.
我想在每个换行符中将第一个字符转换为大写

所以这一段应该是这样的:

This is the first line.
This is the second line.
We live in Europe.
This is the fourth line.
到目前为止,我能够将第一个字符转换为大写,但它使用
ucfirst()
ucword()

有没有办法使用
ucfirst()
preg\u replace()
函数来解决这个问题


谢谢

另一种方法是:

    <?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);
?>

您可以使用这个

<?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;

i
修饰符表示我们不关心大小写,
m
表示字符串的每一行都是
^
的新行。这将大写一行的第一个字母,假定它以a-z开头。

将每行的第一个小写字符替换为大写:

$str = preg_replace_callback(
            '/^\s*([a-z])/m',
            function($match) {
                return strtoupper($match[1]);
            },
            $str);
这个怎么样

$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)));

这有用吗?这些段落是如何生成的?您可以在CSS而不是PHP中执行此操作。
\i
修饰符不需要,因为您已经降低了输入的大小写。此外,我们只需要匹配和替换小写字符,这样就完全不需要了。不过,这会丢弃任何非行起始大写,这通常是不合适的。你可以看到专有名词Europe的大小写较低,代词I的大小写也较低。你能不能用不同的短语@ChrisBaker,或者提供一个不确定我是否遵循的示例。Ulver我注意到了修饰符的作用OP是否可以使用它。我正在做的下半部分是为了说明用法。这里有一个例子:这里的输出:
我们住在欧洲。
预期输出:
我们住在欧洲。
啊,是的,我现在明白你的意思了。OP不应在strtolower中运行其字符串。这只是一个如何实现这一点的正则表达式示例。
$str = preg_replace_callback(
            '/^\s*([a-z])/m',
            function($match) {
                return strtoupper($match[1]);
            },
            $str);
$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)));