使用正则表达式从字符串中提取模式

时间:2015-06-12 05:43:35

标签: php regex

如何使用正则表达式从以下字符串中提取数字和键?

 Duplicate entry '24040446669881344' for key 'clave_something'
 Duplicate entry '24040446669881345' for key 'clave_something_else'

我尝试使用子串,但是当链的长度发生变化时它不会起作用。

谢谢!

2 个答案:

答案 0 :(得分:2)

有了这个,你将从string获得所有整数:

preg_match_all('~\d+~', $string, $match);
print_r($match);

demo

对于您的具体示例,还要提取密钥:

preg_match("~'(.+?)'.+'(.+?)'~", $string, $match);
print_r($match);

demo

或者如果你想获取多行字符串:

preg_match_all("~'(.+?)'.+'(.+?)'~m", $string, $match, PREG_SET_ORDER);
print_r($match);

demo

答案 1 :(得分:2)

试试这个:

preg_match("/Duplicate entry '([^']+)' for key '([^']+)'/", $theString, $matches);

变量$matches将包含您想要的数据。