处理任意联系信息参数的更好方法
我有一张包含联系信息的表格。每个都有一个类型,然后是联系信息本身。例如:
Type | Contact
-------------------------------
cell | 555-555-5555
home | 444-444-4444
email | [email protected]
功能要求是用户可以使用 jQuery 从表单中添加/删除联系人(仅显示存在的联系信息 - 即它不是静态联系表单)。
由于用户可以在表单中添加/删除他们喜欢的任何行,这会产生类似于以下内容的 HTTP 参数(数字不连续,并且可能不连续):
contact_ty3=cell
contact3=555-555-5555
contact_ty994=home
contact994=444-444-4444
contact_ty45=email
[email protected]
因此,contact
之后的数字和 contact_ty 参数是任意的,只不过它们的目的是将类型与关联的联系信息进行匹配。
那么,在接收端,在 PHP 中,如何有效地处理参数,使用数字来匹配类型和联系人?我认为最好的方法是通过正则表达式,但我能想到的最简单的函数会迭代整个 $_REQUEST 数组,去掉以 contact
开头的参数,然后从那里。
有更有效的方法吗?似乎我正在编写一个手动字符串/参数解析方法,但也许有一个我根本不知道的函数可以做到这一点。由于我事先不知道表单参数的准确名称,因此我不能依赖于存在 contact1
、contact2
等的假设。
I've got a form that contains contact info. Each has a type, and then the contact information itself. For example:
Type | Contact
-------------------------------
cell | 555-555-5555
home | 444-444-4444
email | [email protected]
It's a functional requirement that users can add/remove contacts from the form using jQuery (showing only the contact info that exists - i.e. it's not a static contact form).
Since users can add/remove any row they like in the form, this produces HTTP parameters similar to the following (with numbers that are not sequential, and may not be contiguous):
contact_ty3=cell
contact3=555-555-5555
contact_ty994=home
contact994=444-444-4444
contact_ty45=email
[email protected]
Therefore, numbers after the contact
and contact_ty
parameters are arbitrary, except that they serve the purpose to match up the type to the associated contact information.
So, on the receiving end, in PHP, how to I efficiently process the parameters, using the numbers to match up the types and contacts? I'm thinking the best way to do this would be via regex, but the simplest function I can think of iterates through the entire $_REQUEST array, strips out the parameters that start with contact
, and go from there.
Is there a more efficient way? Seems like I'm writing a manual string/param parsing method, when perhaps there's a function to do this that I simply don't know about. Since I won't know the precise names of the form parameters beforehand, I can't rely on the assumption that there will be a contact1
, contact2
, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过一些巧妙的命名,您可以轻松地将它们在帖子中匹配:
在 PHP 中
With some clever naming you can easily match them up on post:
And in PHP
迭代 $_POST 或 $_GET 是一个好主意,而不是 $_REQUEST,因为它可能包含 cookie。但是,最好不要使用正则表达式。您可以使用 substr 来达到此目的。观察
Iterating $_POST or $_GET is a good idea, not $_REQUEST as it might contain cookies. However, its best not to use regex. You can use substr for this purpose. Observe