简体   繁体   English

php preg_match上的连续标签

[英]php preg_match on consecutive tags

I'm trying to capture all Location paths on an apache conf file, to make automatic nginx templates. 我正在尝试捕获apache conf文件上的所有Location路径,以制作自动的nginx模板。

The file that I'm reading has something like this 我正在读取的文件具有以下内容

<Location /images/mobile>
    SetHandler modperl
    PerlOutputFilterHandler Apache2::AMFImageRendering
</Location>
<Location /images/otherroute>
    SetHandler modperl
    PerlOutputFilterHandler Apache2::AMFImageRendering
</Location>

I almost got the regex working with the "location" match group, I had the following 我几乎让正则表达式与“位置”匹配组一起工作,我有以下内容

$file_str = file_get_contents($conf);
preg_match("/<Location\s+(?P<location>.*?)\s*>.*?Apache2::AMFImageRendering.*?<\/Location>/s", $file_str, $matches);
print_r($matches);

The problem is this only get the first location "/images/mobile" inside $matches['location'] 问题是,这只会在$ matches ['location']中获得第一个位置“ / images / mobile”

Is there anyway to match all locations, without splitting the string or using preg_match with an offset 无论如何,有没有匹配所有位置的方法,而无需拆分字符串或使用带有偏移量的preg_match

Thank you 谢谢

You're looking for preg_match_all() . 您正在寻找preg_match_all() This is PHP's answer to the /g modifier of normal regular expressions. 这是PHP对正常正则表达式的/g修饰符的回答。 The 3rd parameter passed ( $matches ) will now contain an array of global match sets. 传递的第三个参数( $matches )现在将包含一个全局匹配集数组。

$file_str = file_get_contents($conf);
preg_match_all("/<Location\s+(?P<location>.*?)\s*>.*?Apache2::AMFImageRendering.*?<\/Location>/s", $file_str, $matches);

print_r($matches);
// Array (
//   [0] => Array
//     (
//       [0] => SetHandler modperl PerlOutputFilterHandler Apache2::AMFImageRendering
//       [1] => SetHandler modperl PerlOutputFilterHandler Apache2::AMFImageRendering
//     )
//   [location] => Array 
//     (
//       [0] => /images/mobile
//       [1] => /images/otherroute
//     )
//   [1] => Array
//     (
//       [0] => /images/mobile
//       [1] => /images/otherroute
//     )
//  )

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

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