使用 preg_match_all() 和结束字符匹配一个字符串中的多个项目
我有以下代码:
preg_match_all('/(.*) \((\d+)\) - ([\d\.\d]+)[,?]/U',
"E-Book What I Didn't Learn At School... (2) - 3525.01, FREE Intro DVD/Vid (1) - 0.15",
$match);
var_dump($string, $match);
并获得以下输出:
array(4) {
[0]=>
array(1) {
[0]=>
string(54) "E-Book What I Didn't Learn At School... (2) - 3525.01,"
}
[1]=>
array(1) {
[0]=>
string(39) "E-Book What I Didn't Learn At School..."
}
[2]=>
array(1) {
[0]=>
string(1) "2"
}
[3]=>
array(1) {
[0]=>
string(7) "3525.01"
}
}
仅匹配一项...我需要的是从此类字符串中获取所有项目。当我在字符串末尾添加“,”符号时 - 它工作得很好。但这在每个字符串中添加逗号是没有意义的。有什么建议吗?
I have the following code:
preg_match_all('/(.*) \((\d+)\) - ([\d\.\d]+)[,?]/U',
"E-Book What I Didn't Learn At School... (2) - 3525.01, FREE Intro DVD/Vid (1) - 0.15",
$match);
var_dump($string, $match);
and get the following ouput:
array(4) {
[0]=>
array(1) {
[0]=>
string(54) "E-Book What I Didn't Learn At School... (2) - 3525.01,"
}
[1]=>
array(1) {
[0]=>
string(39) "E-Book What I Didn't Learn At School..."
}
[2]=>
array(1) {
[0]=>
string(1) "2"
}
[3]=>
array(1) {
[0]=>
string(7) "3525.01"
}
}
which matches only one items... what i need is to get all items from such strings. when i've added "," sign to the end of the string - it worked fine. but that is non-sense in adding comma to each string. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个正则表达式:
主要的区别是你有
.*
(贪婪),我用.*?
(非贪婪)替换。您首先“吃掉”整个字符串(除了换行符),然后回溯以仅匹配字符串中的一个片段。演示:
产生:
Try this regex:
The major difference is that you had
.*
(greedy) which I replaced with.*?
(un-greedy). Yours first "ate" the entire string (except line breaks) and then back tracked to match just one piece from your string.Demo:
produces: