开发者

How do I allow for user input of words sparated by commas and spaces? PHP

what I am trying to do is allow for users to input keywords sparated by a comma and a space (ex: word, word, word, wor开发者_StackOverflowd). There is no limit on the number of words or anything, I would simply like the format to be respected. Thank you!


Well if you wanted to be exact you would use:

$tags = explode(', ',$input);

A more happy matching without using regex:

$tags = explode(',',$input);
for($i=0;$i<count($tags);$i++) {
    $tags[$i] = trim($tags[$i]);
}

And using regular expressions:

$tags = preg_split('/\s*,\s*/',$input,-1,PREG_SPLIT_NO_EMPTY);


you can simply use explode to split a string into part's.

$words = explode(', ',$_POST['words']);


You can reformat user input on server-side and don't force them to worry about format. Just write function to do it for you. Something like

  $correct_input = reformatInput($user_input);

Function reformatInput() might be like this one

  function reformatInput($inp) {
    $inparr = explode(" ", str_replace(",", " ", $inp));
    $res = array();
    foreach ($inparr as $item) if ($item != '') $res[] = $item;
    return join(", ", $res); // join() is alias of implode()
    }

This function returns string containing words separated with comma+space or empty string if there are no words in user's input.

Now if you have user input like this one for example

  $user_input = "  word1,word2,   word3,, word4, word5 word6 word7  ,,,";

you can reformat it using that function and output in correct format

  $correct_input = reformatInput($user_input);
  echo "user input ($correct_input)";

Output based on this example will be

user input (word1, word2, word3, word4, word5, word6, word7)

Generally, that's result what you want in first place.

Note: You can use Ajax to reformat their input, onExit event of input element and store it back (correct format) in that input field, or rewrite this function in JavaScript and do it at client-side, but in that case, you should check it on server side again and it doesn't work if client disables JavaScript in his/hers browser.

You can do it without regular expressions as you can see, easily.


References:

  • explode()
  • join(), or its alias implode()
  • foreach loop
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜