【问题标题】:Using array_map to replace spaces between characters使用 array_map 替换字符之间的空格
【发布时间】:2012-07-31 23:06:06
【问题描述】:

我正在用逗号分隔值的字符串创建一个数组

$result = "apple, hello word, 80, apple";    

$result = str_getcsv($result); //create array     
$result = array_filter(array_map('trim', $result)); //remove whitespaces

值中的某些字符之间有空格,例如hello world,我想用破折号替换空格(以使字符串 URL 友好。)示例:hello-world

我曾想过使用 str_replace 遍历数组,但使用 array_map 是否可以做得更好,就像我正在做的修剪一样?

【问题讨论】:

  • 如果您使用的是 PHP 5.3,您可以编写一个函数来执行您想要的处理,或者使用闭包(匿名函数)。

标签: php arrays string


【解决方案1】:

str_replace 也可以直接作用于数组:

$result = str_replace(' ', '-', $result);

这将与可读性差的结果相同

$result = array_map(function($el) { return str_replace(' ','-',$el); }, $result);

两者也都等价于经典

foreach($result as &$element) {
    $element = str_replace(' ', '-', $element);
}

【讨论】:

    【解决方案2】:

    试试

    function urlFrendly($str){
        return str_replace(' ', '-', $str);
    }
    
    $result = "apple, hello word, 80, apple";    
    
    $result = str_getcsv($result); //create array     
    $result = array_filter(array_map('trim', $result)); //remove whitespaces
    $result = array_map('urlFrendly', $result); 
    var_dump($result);
    

    【讨论】:

      【解决方案3】:
      $result = "apple, hello word, 80, apple";
      $replaced = preg_replace('/\s*([[:alpha:]]+) +([[:alpha:]]+)\s*/', '\\1-\\2',$result);
      $array = str_getcsv($replaced);
      print_r($array);
      

      输出:

      Array
      (
      [0] => apple
      [1] => hello-word
      [2] => 80
      [3] => apple
      )
      

      【讨论】:

        猜你喜欢
        • 2014-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 2015-08-09
        相关资源
        最近更新 更多