Michael S
Michael S

Reputation: 13

Replace whitespace in array in PHP

I have an index page that takes a user input list of items separated by a space. It processes that list as an array and replaces the white space with a ", ". However, my PHP script doesn't seem to do that and I'm not sure I understand why.

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";

?>

Any help in understanding this would be greatly appreciated! Thanks!

EDIT Thanks a lot everyone! Seems like my issue was a fairly novice one and fixing it was pretty easy.

Upvotes: 1

Views: 3231

Answers (3)

unxp
unxp

Reputation: 358

  1. Remove [] from input name:

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. Do you really need regular expressions here? Use strtr() as it is more efficient:

process.php

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

Upvotes: 2

Phil Cross
Phil Cross

Reputation: 9302

Probably because you're running preg_replace on an array.

Instead, try use 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']

Alternatively, if you want to do the same for a string:

$string = 'This is some test string';

print_r(str_replace(' ', ', ', trim($string)));

Upvotes: 1

NaijaProgrammer
NaijaProgrammer

Reputation: 2957

That is because you set the input name to list[] which is submitted to the server side script as an array. To process, you have two options:

  1. Change the input type to <input name="list" type="text">, and leave the server side script as you currently have it. Notice the "list" has no braces [] after it.

  2. Leave the front end HTML as you currently have it and update your server side code thus:

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

Upvotes: 0

Related Questions