将多行联系人卡片解析为单独的变量
我想获取以这种格式输入的数据:
John Smith
123 Fake Street
Fake City, 55555
http://website.com
并将值存储在变量中,如下所示:
$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';
- 名称将是第一行上输入的任何内容
- 地址是第二行上输入的任何内容
- 城市是第三行逗号分隔符之前输入的任何内容
- zip 是第三行逗号后面的内容 网站
- 是第五行的内容。
我不希望模式规则比这更严格。有人可以展示如何做到这一点吗?
I want to take data entered in this format:
John Smith
123 Fake Street
Fake City, 55555
http://website.com
and store the values in variables like so:
$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';
- name will be whatever is entered on the first line
- address is whatever is on the second line
- city is whatever is entered on the third line before the comma separator
- zip is whatever is on the third line after the comma
and - website is whatever is on the fifth line.
I don't want the pattern rules to be stricter than that. Can someone please show how this can be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,正则表达式可能类似于:
假设
\r
是换行符分隔符。当然,使用explode()
之类的东西来分割会更容易事物在线条中...Well, the regex would probably be something like:
Assuming that
\r
is your newline separator. Of course, it'd be even easier to use something likeexplode()
to split things in to lines...如果你想要更精确的东西,你可以使用这个:
干杯
If you want something more precise, you could use this:
cheers
sscanf()
旨在解析可预测格式的文本。它可以返回捕获子字符串的数组,填充引用变量(如果它们被声明为参数)。只需知道每个占位符都会贪婪地匹配,
%s
不会跨越空格,一旦不满足占位符,捕获就会停止,并且后续变量将不会被分配。代码:(演示)
输出:
sscanf()
is designed to parse predictably formatted text. It can return an array of captured substrings, populate reference variables if they are declared as parameters.Just know that each placeholder will greedily match,
%s
will not cross a whitespace, and capturing will halt as soon as a placeholder is not satisfied and subsequent variables will not be assigned.Code: (Demo)
Output: