【问题标题】:Replace whitespace in array in PHP替换PHP中数组中的空格
【发布时间】:2015-09-15 22:50:15
【问题描述】:

我有一个索引页面,它采用由空格分隔的用户输入项目列表。它将列表作为数组处理,并用“,”替换空格。但是,我的 PHP 脚本似乎没有这样做,我不确定我理解为什么。

index.php

<form action="process.php" method="post">
    <b>Enter a list of items separated by a space:</b> <br><input name="list[]" type="text">
    <input type="submit">
</form>

process.php

<?php
$list = $_POST["list"];
$list = preg_replace('#\s+#',', ',trim($list));
echo "<b>Your listed items were:</b> $list";

?>

任何帮助理解这一点将不胜感激!谢谢!

编辑 非常感谢大家!似乎我的问题是一个相当新手的问题,解决起来很容易。

【问题讨论】:

  • $list 是一个输入数组。将其作为数组处理
  • 使用$list = explode(' ', $list); 这将使它成为一个数组。然后,您可以遍历发布值的数组。

标签: php arrays whitespace removing-whitespace


【解决方案1】:
  1. 从输入名称中删除 []:

index.php

<form action="process.php" method="post">
    <b>Enter a list of items separated by a space:</b> <br><input name="list" type="text">
    <input type="submit">
</form>
  1. 这里真的需要正则表达式吗?使用strtr() 效率更高:

process.php

<?php
$list = $_POST["list"];
$list = strtr(trim($list), ' ', ',');
echo "<b>Your listed items were:</b> $list";
?>

【讨论】:

    【解决方案2】:

    可能是因为您在数组上运行 preg_replace。

    请尝试使用array_walk:

    $list = array('this', 'is a', 'test');
    
    array_walk($list, function(&$v){
        $v = str_replace(' ', ', ', trim($v));
    });
    
    
    print_r(implode(', ', $list));
    
    // Outputs: this, is, a, test
    
    print_r(explode(', ', implode(', ', $list)));
    
    // Outputs: ['this', 'is', 'a', 'test']
    

    或者,如果你想对字符串做同样的事情:

    $string = 'This is some test string';
    
    print_r(str_replace(' ', ', ', trim($string)));
    

    【讨论】:

      【解决方案3】:

      那是因为您将输入名称设置为list[],它作为数组提交给服务器端脚本。要处理,您有两种选择:

      1. 将输入类型更改为&lt;input name="list" type="text"&gt;,并将服务器端脚本保留为您当前的脚本。请注意,“列表”后面没有大括号 []

      2. 保留您当前拥有的前端 HTML 并更新您的服务器端代码:

        $lists = $_POST["list"]; //this comes in as an array from the HTML form
        $str = '';
        foreach($lists AS $list)
        {
            $str .= preg_replace('#\s+#',', ',trim($list));
        }
        echo "<b>Your listed items were:</b> $str";
        

      【讨论】:

      • 这肯定更有意义。在数组上使用 preg_replace 是不好的做法吗?
      • 如果您必须在数组上使用preg_replace,那么您必须将它与一个array_walk_* 系列函数一起使用。正如preg_replace 通常与字符串参数一起使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2016-06-16
      • 2011-02-20
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多