Php 使用正则表达式读取自己的间隔

Php 使用正则表达式读取自己的间隔,php,regex,Php,Regex,您好这是我的文本内容 data1='res1', data2='res2', data3 = 'anything like data5='', get complete', data4 = 'anything' 我想使用php正则表达式获取所有(数据)和(数据值),但存在问题。我的问题是data3value(类似data5='',请完成)contentdata5=''和data5的值不是数据键在我的程序中,data5作为独立键进行检测,而这只是data3的值,必须在我的正则表达式中的所有值数组

您好这是我的文本内容

data1='res1', data2='res2', data3 = 'anything like data5='', get complete', data4 = 'anything'

我想使用php正则表达式获取所有(数据)和(数据值),但存在问题。我的问题是
data3
value
(类似data5='',请完成)
content
data5=''
data5
的值不是数据键
在我的程序中,
data5
作为独立键进行检测,而这只是
data3
的值,必须在我的正则表达式中的所有值数组中进行检测。
我可以使用什么正则表达式来解决这个问题,正则表达式读取
data1
data2
data3
data4
与(
rest1
res2
,(任何类似于
data5='
get complete
),任何内容)?

如果数据结构是固定的,您可以使用以下内容:

$re = "~ ([^\W_]+) \h*=\h* '(.*?)' \h*,\h*
         ([^\W_]+) \h*=\h* '(.*?)' \h*,\h*
         ([^\W_]+) \h*=\h* '(.*?)' \h*,\h*
         ([^\W_]+) \h*=\h* '(.*?)'         ~x";

$subst = " $1 -> $2\n $3 -> $4\n $5 -> $6\n $7 -> $8\n";

$data = "data1='res1', data2='res2', data3 = 'anything like data5='', get complete', data4 = 'anything'\n\ndata1='res1', data2='res2', data3 = 'anything like data5=''', data4 = 'anything'\n# Odds single quote\ndata1=''res1', data2='res2', data3 = 'anything like data5=''', data4 = 'anything'\n# Even quotes inside data1\ndata1='''res1', data2='res2', data3 = 'anything like data5=''', data4 = 'anything'";

$result = preg_replace($re, $subst, $data);

print_r($result);
输入

data1='res1',data2='res2',data3='任何类似data5='''的内容,获取完整信息',data4='任何内容'

输出

数据1->res1
数据2->res2
data3->任何类似data5=''的内容,请完成
数据4->任何东西


正则表达式突破

所有4个部分

单个数据部分的详细信息(例如数据1)


编辑完成。请阅读3行结尾。@Justmyhope2016:我以“如果数据结构是固定的”,如果您有不同形式的输入,请更新问题。惰性正则表达式需要一个锚来正确操作,在您的情况下,使用
([^\W\uz]+)\h*=\h*'(.*)$
是最简单的解决方法(但如果您想要一个对所有输入都有效的完整答案,请更新问题)。
~                                 # regex start delimiter
([^\W_]+) \h*=\h* '(.*?)' \h*,\h* # data1
([^\W_]+) \h*=\h* '(.*?)' \h*,\h* # data2
([^\W_]+) \h*=\h* '(.*?)' \h*,\h* # data3
([^\W_]+) \h*=\h* '(.*?)'         # data4
~x                                # close delimiter with 'x' freespace flag
([^\W_]+) # 1 or more alphanumeric chars (equal to [a-zA-Z0-9])
          # the round brackets save them in $1 group
\h*=\h*   # zero or more horizontal whitespace chars then a literal '='
          # followed by zero or more whitespace chars again
'(.*?)'   # a single quote "'", zero o more chars of any type, closing quote "'"
          # the lazy modifiers '?' makes it stop at the first single quote 
          # that satisfy also the rest of the regex(!)
\h*,\h*   # zero or more horizontal whitespace chars then a literal comma ','
          # followed by zero or more whitespace chars again