Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:一次获取长字符串中出现的所有字符串_Php_Regex_String - Fatal编程技术网

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+)”。非常感谢你的帮助