简体   繁体   English

我如何获得表单以在提交之前删除链接的一部分?

[英]how do i get a form to remove part of a link before submit?

Say i had a form input to submit a facebook user id, but some don't read and submit the whole link how do i remove the part of the link i don't want, before form submit? 说我有一个表单输入来提交一个Facebook用户ID,但是有些人没有阅读并提交整个链接,在表单提交之前,我如何删除我不需要的链接部分?

<form>
Facebook id: <input type="text" name="facebookid">
</form>

and the user enters this: 然后用户输入以下内容:

www.facebook.com/UserProfleID www.facebook.com/UserProfleID

How do i get it to remove the "www.facebook.com/" and just leave the ID? 我如何删除“ www.facebook.com/”并仅保留ID? before submit? 提交之前?

Thanks heaps for your time, any help would be great 感谢您的宝贵时间,任何帮助都将是非常有用的

If you are the one receiving the form , you can just play with the string before starting to work with it. 如果您是收到表格的人 ,则可以在开始使用它之前先使用它。 You could delete the substring you dont want using str_replace : 您可以使用str_replace删除不需要的子字符串:

str_replace('www.facebook.com/', '', $input);
str_replace('facebook.com/', '', $input);
str_replace('http://facebook.com', '', $input);

Although I would recommend you to use regular expressions with preg_match . 尽管我建议您将正则表达式与preg_match一起使用。

If you have no control after the submission of the form, then you can use Javascript and make use of the split function: 如果提交表单后您没有控制权 ,则可以使用Javascript并使用split函数:

//str = input string
var parts = str.split("facebook.com/");

//alerting the username
alert(parts[1]);

You could intercept the form submit with javascript and let the user know they made an error. 您可以使用javascript拦截表单提交,并让用户知道他们犯了一个错误。 But as others have said you should still validate on the server. 但是正如其他人所说,您仍然应该在服务器上进行验证。

document.forms[0].onsubmit = function(){
     var input = document.getElementsByName('facebookid')[0].split("/");
     if(input.length > 1){ 
         //should do this part with fancy CSS and not an alert box
         alert("Enter your id only plix plox");
         return false;
      }
     return true;
}
<form>
Facebook id: <input type="text" id="userid" name="facebookid">
</form>



$("form").submit( function () {
var arr= $("#userid").val().split("facebook.com/");
$("#userid").val(arr[1]);
} );

It might help you. 它可能会帮助您。

If you expect the prefix to be predictable, then you can use a dictionary of strings you can Remove from the input. 如果希望前缀是可预测的,则可以使用可以从输入中删除的字符串字典。

However, if you're not able to predict the input, then Regular expressions give you the flexibility to predict the pattern but not the value to be removed. 但是,如果您无法预测输入,则使用正则表达式可以灵活地预测模式,但不能预测要删除的值。

I would use RegularExpressions if this were my code...largely because I'm fan of writing the least code to do the most work. 如果这是我的代码,我会使用RegularExpressions ...主要是因为我喜欢编写最少的代码来完成最多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM