PHP:立即在长字符串中获取字符串的所有出现

时间:2016-01-28 21:53:49

标签: php regex string

我有一个非常长的字符串,我想从中获取数据。在字符串中有一个类似的部分重复了很多次。例如:

...
Price: 1,540
Ref No.: x24345543              
 
Shape: square              
Size: 12.91            
...
Price: 2,222
Ref No.: ydeft              
 
Shape: triangle  maybe_something_else_which_is_not_needed        
Size: 11.11       
...

我知道我可以使用strpossubstr的组合,但我想我需要使用strpos两次和substr一次才能获得一个项目然后再次在整个字符串中使用各自的函数。

有没有更快的解决方案来实现这一目标?

1 个答案:

答案 0 :(得分:1)

这可以通过以下正则表达式完成:

~^((?! |\.+)[^:]+):\s*(\S+)~
# ^ - anchor to the start
# (?!) - negative lookahead - no   or lines of dots
# match everything except a colon and capture it to group 1
# match a colon, some whitspaces
# capture everything that is not a whitespace into group 2

查看此approach on regex101.com的演示 转换为PHP代码,这将是:

$regex = '~^((?! |\.+)[^:]+):\s*(\S+)~gm';
preg_match_all($regex, $string, $matches);
foreach ($matches as $match) {
    // improve the world with it
    echo "Category: " . $match[1] . ", value: " . $match[2] . "\n";
}