【问题标题】:Convert the first character to uppercase in every newlines in php将php中每个换行符的第一个字符转换为大写
【发布时间】:2015-06-05 16:15:26
【问题描述】:

我有以下段落:

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() 函数来解决这个问题?

谢谢!

【问题讨论】:

标签: php


【解决方案1】:

这个怎么样?

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

【讨论】:

    【解决方案2】:

    你可以用这个。

    <?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 开头。

    【讨论】:

    • \i 修饰符不是必需的,因为您已经将输入小写。此外,我们只需要匹配和替换小写字符,因此根本不需要。
    • 这会丢弃任何非行首大写,但这通常是不合适的。您可以看到专有名词 Europe 是小写的,代词 I 也是如此。
    • 您能否以不同的方式表达@ChrisBaker,或者提供一个不确定我是否遵循的示例。 Ulver 我注意到 OP 可以使用或不使用什么修饰符。我做的小写是为了说明用法。
    • 这里是一个例子:在这里输出:We live in europe. 预期输出:We live in Europe.
    • 啊,是的,我现在明白你的意思了。 OP 不应通过strtolower 运行他们的字符串。这只是一个如何实现的正则表达式示例。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      另一种方法是:

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

      【讨论】:

        猜你喜欢
        • 2017-07-23
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多