简体   繁体   English

PHP preg_match正则表达式捕获字符串中的模式

[英]PHP preg_match regex capturing pattern in a string

I can't seem to get Regular Expressions right whenever I need to use them ... 每当我需要使用正则表达式时,似乎都无法正确使用正则表达式...

Given a string like this one: 给定这样的字符串:

$string = 'text here [download="PDC" type="A"] and the text continues [download="PDS" type="B"] and more text yet again, more shotcodes might exist ...';

I need to print the "text here" part, then execute a mysql query based on the variables "PDC" and "A", then print the rest of the string... (repeating all again if more [download] exist in the string). 我需要打印“此处的文本”部分,然后根据变量“ PDC”和“ A”执行mysql查询,然后打印其余的字符串...(如果存在更多[下载],请重复所有步骤)串)。

So far I have the following regex 到目前为止,我有以下正则表达式

$regex = '/(.*?)[download="(.*?)" type="(.*?)"](.*?)/';
preg_match($regex,$string,$res);
print_r($res);

But this is only capturing the following: 但这仅捕获以下内容:

Array ( [0] => 111111 [1] => 111111 [2] => ) 

I'm using preg_match() ... should I use preg_match_all() instead? 我正在使用preg_match()...我应该改为使用preg_match_all()吗? Anyway ... the regex is surely wrong... any help ? 无论如何...正则表达式肯定是错误的...有帮助吗?

[ opens character class, and ] finishes it. [打开字符类,然后]完成。 Such characters with meaning need to be either escaped or put into a QE block in PCRE regex. 此类具有含义的字符需要转义或放入PCRE regex中的QE块中。

/(.*?)\Q[download="\E(.*?)" type="(.*?)"](.*?)/
      ##^          ##         ^-- you were looking for "tipo"
        |
  this character needs to be taken literal, hence the \Q....\E around it
                                                      ##    ##

Try it with with "little" one 与“小”一个一起尝试

/(?P<before>(?:(?!\\[download="[^"]*" type="[^"]*"\\]).)*)\\[download="(?P<download>[^"]*)" type="(?P<type>[^"]*)"\\](?P<after>(?:(?!\\[download="[^"]*" type="[^"]*"\\]).)*)/

It will provide you the keys before , after , download and type in the matches result. 它会after download beforeafterdownload after type匹配项并为您提供密钥。

Test it here: http://www.regex101.com/r/mF2vN5 在这里测试: http : //www.regex101.com/r/mF2vN5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM