PHP:一次获取长字符串中出现的所有字符串
我有一个很长的字符串,我想从中获取数据。在字符串中有一个相似的部分重复了很多次。例如:PHP:一次获取长字符串中出现的所有字符串,php,regex,string,Php,Regex,String,我有一个很长的字符串,我想从中获取数据。在字符串中有一个相似的部分重复了很多次。例如: ... Price: 1,540 Ref No.: x24345543 Shape: square Size: 12.91 ... Price: 2,222 Ref No.: ydeft Shape: tr
...
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
...
我知道我可以使用strop
和substr
的组合,但我想我需要使用strop
两次和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
请参见演示。翻译成
PHP
code,这将是:
$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";
}
使用正则表达式??谢谢。输入字符串如Price:1540参考号:x24345543形状:正方形大小:12.91@koubin:请编辑您的原始问题,并在其中放入一些示例字符串。谢谢。你的例子很好。有没有一种方法可以消除像本例中那样的额外的“ ”(行开始处甚至可能是空格)?我可能只需要数据,所以我发现正则表达式的这部分就足够了:“:\s*(\s+)”。非常感谢你的帮助