【问题标题】:Make every first character uppercase in array使数组中的每个第一个字符大写
【发布时间】:2022-02-17 10:45:35
【问题描述】:

我正在尝试将 PHP 数组中的所有第一个字符都设为大写。

PHP 代码:

<?php
$ordlista = file_get_contents('C:/wamp/www/bilder/filmlista.txt');

$ord = explode("\n", $ordlista);

sort($ord,SORT_STRING);

foreach ($ord as $key => $val) {
    echo $val."<br/>";
}
?>

【问题讨论】:

  • 我们没有任何样本数据。文件中每行只有一个单词吗?任何多字节字符?单词都是小写的吗?

标签: php arrays


【解决方案1】:
$ord = array_map('ucfirst', $ord);

【讨论】:

  • 或者像这样使用匿名函数:
    $ord = array_map(create_function('$value', 'return ucfirst($value);'), $ord);
【解决方案2】:
$ord=array_map(function($word) { return ucfirst($word); }, $ord);

【讨论】:

  • 不起作用...注意:使用未定义的常量 ucwords - 在第 5 行的 C:\wamp\www\sorting\sort.php 中假定为“ucwords”警告:array_map() 需要参数1 是一个有效的回调,数组必须在第 5 行的 C:\wamp\www\sorting\sort.php 中恰好有两个成员警告:sort() 期望参数 1 是数组,在 C:\wamp\www 中给出 null第 7 行的 \sorting\sort.php 警告:为第 9 行 C:\wamp\www\sorting\sort.php 中的 foreach() 提供的参数无效
  • @Victor:现在试试。出于某种原因,它不喜欢 ucwords 作为回调,它必须被包裹在一个闭包中。
  • @icktoofay 这不是真正的闭包,而是一个匿名函数。而且PHP中的函数不是一等的,所以array_map(ucfirst)不行,正确的语法是array_map('ucfirst')
  • @deceze:我的印象是它是一个闭包,因为如果你在 PHP CLI 解释器中运行它:&lt;?php $hello=function() { echo "hello\n"; }; echo $hello; ?&gt;,你会收到一条错误消息 Object of class Closure could not be converted to string。对我来说,这说明它是一个闭包。
  • As the manual states: Anonymous functions are currently implemented using the Closure class. This is an implementation detail. 如果它关闭外部范围的变量(使用use),这将是一个闭包,但它没有做。我猜 Closure 类用于任何匿名函数,因为它是闭包的子集。诚然,这是一个很好的区别。 [维基百科甚至提到](en.wikipedia.org/wiki/Closure_(computer_science%29):The term closure is often mistakenly used to mean anonymous function.
【解决方案3】:

要支持 UTF-8 多字节字符,例如“俄语”,您需要

$ord = array_map(function($str){
    return mb_strtoupper(mb_substr($str, 0, 1)).mb_strtolower(mb_substr($str, 1));
}, $ord);

这使用来自https://stackoverflow.com/a/14161325/175071mb_ucfirst 函数

【讨论】:

    【解决方案4】:

    有时,原始数据看起来像这样:

    $ord = ['apple', 'GUAVA', 'mango', 'BANANA'];
    

    为了充分证明这一点:

    $ord = array_map('ucfirst', array_map('strtolower', $ord));
    

    它的作用是首先将所有内容转换为小写,然后将每个单词大写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2010-12-25
      • 1970-01-01
      相关资源
      最近更新 更多