你好,这是我的字符串
data {'1' => 'anything', '2' => '5', '3' => 'anything'}
data {'1' => 'anything', '2' => '5', '3' => 'anything', '7' => 'anything'}
data {'1' => 'anything', '2' => '6', '3' => 'anything'}
data {'1' => 'anything', '5' => 'anything', '2' => '5', '3' => 'anything'}
我想使用正则表达式并获取其中存在'2' => '5'
的每一行。
有些人喜欢这个
数据{之前的所有内容('2' => '5'
)之后的所有内容}
我的问题是如何在我想要的之前和之后传递所有内容('2' => '5'
)?
data\h*[{](what should i use here to pass everything exists before)[']2[']\h*[=][>]\h*[']5['](what should i use here to pass everything exists after)[}]
得到这一行
data {'1' => 'anything', '2' => '5', '3' => 'anything'}
data {'1' => 'anything', '2' => '5', '3' => 'anything', '7' => 'anything'}
data {'1' => 'anything', '5' => 'anything', '2' => '5', '3' => 'anything'}
请修复我的正则表达式
感谢您的回答,但还有一个问题..如果我的字符串是
data {'1' => 'anything
anynew line inside of 1', '2' => '5', '3' => 'anything'}
data {'1' => 'anything', '2' => '5', '3' => 'anything', '7' => 'anything'}
data {'1' => 'anything', '2' => '6', '3' => 'anything'}
data {'1' => 'anything', '5' => 'anything', '2' => '5', '3' => 'anything'}
(我在行中''
使用新行和其他所有内容)它不会获得该行!!!!!!!!!!!!!我该怎么办? .*
当我在每行内有多行时不起作用 我需要在!!!之前和之后获取所有内容(包括行和...)
答案 0 :(得分:0)
要捕获一个或多个'key' => 'value',
部分,请使用此选项:
((\s*'[^']*'\s*=>\s*'[^']*'\s*,\s*)*)
但是,您可以检查一行是否包含您的字符串而没有完整匹配模式:
preg_match("#'2' => '5'#", $line);
更新:如果您想捕获多行文字,请使用严格匹配的模式:
$content = "data {'1' => 'anything
anynew line inside of 1', '2' => '5', '3' => 'anything'}
data {'1' => 'anything', '2' => '5', '3' => 'anything', '7' => 'anything'}
data {'1' => 'anything', '2' => '6', '3' => 'anything'}
data {'1' => 'anything', '5' => 'anything', '2' => '5', '3' => 'anything'}";
preg_match_all("#data\\s*\\{((\\s*'[^']*'\\s*=>\\s*'[^']*'\\s*,\\s*)*)\\s*'2'\\s*=>\\s*'5'\\s*((\\s*,\\s*'[^']*'\\s*=>\\s*'[^']*'\\s*)*)#", $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo "BEFORE: " . $match[1] . "<br />";
echo "AFTER: " . $match[3] . "<br />";
echo "<hr />";
}
我注意:如果您是谁生成此数据,则应使用更好的格式。例如, JSON流是多线内容数据结构的良好解决方案。您可以轻松找到适用于PHP的JSON流解析器。