php 用空格和数组中的大写第一个字符替换下划线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29405786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:23:39  来源:igfitidea点击:

Replace underscore with space and upper case first character in array

phparrays

提问by Sadikhasan

I have the following array.

我有以下数组。

$state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");

Expected Output

预期产出

$state = array("Gujarat","Andhra Pradesh","Madhya Pradesh","Uttar Pradesh");

I want to convert array values with each first character of a word with UpperCaseand replace _with space. So I do it using this loop and it working as expected.

我想数组值转换成一个字的每个第一个字符UpperCase和替换_space。所以我使用这个循环来做它并且它按预期工作。

foreach($states as &$state)
 {
    $state = str_replace("_"," ",$state);
    $state = ucwords($state);
 }

But my question is: is there any PHP function to convert the whole array as per my requirement?

但我的问题是:是否有任何 PHP 函数可以根据我的要求转换整个数组?

回答by agamagarwal

You can use the array_mapfunction.

您可以使用该array_map功能。

function modify($str) {
    return ucwords(str_replace("_", " ", $str));
}

Then in just use the above function as follows:

然后只需使用上述功能,如下所示:

$states=array_map("modify", $old_states)

回答by Narendrasingh Sisodia

Need to use array_mapfunction like as

需要使用array_map像 as

$state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");
$state = array_map(upper, $state);
function upper($state){
    return str_replace('_', ' ', ucwords($state));
}
print_r($state);// output Array ( [0] => Gujarat [1] => Andhra pradesh [2] => Madhya pradesh [3] => Uttar pradesh )

回答by phpPhil

PHP's array_mapcan apply a callback method to each element of an array:

PHP 的 array_map可以对数组的每个元素应用回调方法:

$state = array_map('makePretty', $state);

function makePretty($value) 
{
    $value= str_replace("_"," ",$value);
    return ucwords($value);
}

回答by PravinS

Use array_map()function

使用array_map()功能

<?php
    function fun($s)
    {
        $val = str_replace("_"," ",$s);
        return ucwords($val);
    }
    $state = array("gujarat","andhra_pradesh","madhya_pradesh","uttar_pradesh");
    $result = array_map('fun',$state);
    print_r($result);
?>