如何允许用户输入用逗号和空格分隔的单词?PHP


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

我想做的是允许用户输入由逗号和空格分隔的关键字(例如:word, word, word, word)。没有字数限制或任何东西,我只是希望格式得到尊重。谢谢你!

如果你想更准确,你可以使用:

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

不使用regex的更愉快匹配:

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

和使用正则表达式:

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

您可以简单地使用explode将字符串拆分为部分。

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

您可以在服务器端重新格式化用户输入,而不必强迫他们担心格式问题。只要写一个函数就可以了。就像

  $correct_input = reformatInput($user_input);

函数reformatInput()可能像这样

  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()
    }

此函数返回字符串,其中包含以comma+space分隔的单词,如果用户输入中没有单词,则返回空字符串

现在如果你有像这样的用户输入例如

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

您可以使用该函数重新格式化,并以正确的格式输出

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

基于此示例的输出将是

用户输入(word1, word2, word3, word4, word5, word6, word7)

一般来说,这就是你想要的结果。

注意:您可以使用Ajax重新格式化输入,输入元素的onExit事件并将其存储在该输入字段中(正确格式),或在JavaScript中重写此函数并在客户端执行,但在这种情况下,您应该在服务器端再次检查它,如果客户端在他/她的浏览器中禁用JavaScript则不起作用。

您可以不使用正则表达式来实现它,正如您所看到的,很容易。


引用:

  • 爆炸()
  • join()或其别名implode()
  • foreach循环