PHP:一次获取长字符串中所有出现的字符串



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

...
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一次才能只得到一个项目,然后再次使用整个字符串上的每个函数。

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

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

~^((?! |.+)[^:]+):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
请参阅

有关此方法的演示,请参阅 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";
}

最新更新