如何在 url 中的字符串之间添加连字符


How to add hyphen in between strings in url

我有一个表单,其中有一个文本字段和提交按钮.单击提交按钮时,它会转到下一个PHP页面。用户可以在文本字段中输入文本。文本字段可以包含 n 个以空格分隔的文本字符串。就像用户输入文本一样我的名字是彼得我希望文本在网址中更改为我的姓名是彼得。当用户单击"提交"按钮时,URL 应变为 submit.php?search=MY-name-is-peter

<form action="submit.php" method="get">
<input type="text" name="search" id="search">
<input type="submit" name="submit" value="submit">
</form>

有关如何在 url 的字符串中添加连字符的轻松指南。

<script>
var handler = function (element) {
  element.form.search.value = element.form.search.value.replace(/ /g, '-');
};
</script>

<form action="" method="get">
  <input type="text" name="search" id="search" />
  <input type="submit" onclick="handler(this);" name="submit" value="submit" />
</form>

>str_replace可以工作,或者如果你想使用正则表达式,你可以尝试preg_replace("/[-]/", ", $yourString)

您应该在提交之前对 URL 进行编码:

  $('form').submit(function(){
  var val = $(this).find('#search').val();
  $(this).attr('action','submit.php'+encodeURI(val))
 })

例 : http://jsfiddle.net/e3L3a/