简体   繁体   English

preg_match搜索

[英]preg_match search

<?php
$content = "
{php
    {php 1 php}
    {php 2 php}
    {php 3 php}
php}"; 

How I can get 4 strings? 我怎么能得到4个字符串?

First: 第一:

{php 1 php}
{php 2 php}
{php 3 php}

Second: 第二:

1

Third: 第三:

2

Four: 四:

3

While you could easily parse such input with a simple counter, it is possible to use a recursive regex to get what you want. 虽然您可以使用简单的计数器轻松解析此类输入,但可以使用递归正则表达式来获取所需内容。 A simple (?) regex to validate the input would be: 一个简单的(?)正则表达式来验证输入将是:

^({php\s*(\d+|(?1)+)\s*php}\s*)$

(?1) is a recursive match, it tries to match the first group again, which is another {php ... php} token. (?1)是一个递归匹配,它试图再次匹配第一个组,这是另一个{php ... php}标记。 We also have a capturing group between the php s to capture their content. 我们还在php之间有一个捕获组来捕获它们的内容。

In your case you want to capture overlapping results (in fact, even results contained within other results). 在您的情况下,您希望捕获重叠结果(事实上,甚至包含在其他结果中的结果)。 This is even less pretty, but still possible, using a look-ahead. 这甚至不那么漂亮,但仍然可以使用前瞻。 Look-around can have capturing groups, so the pattern would be: 环视可以有捕获组,因此模式将是:

(?=({php\s*(\d+|(?1)+)\s*php}\s*))

The result has a two extra captured groups - blank results for the look around, and the whole token with the outer {php ... php} , but if you use PREG_PATTERN_ORDER your expected results will be on the third postion ( [2] ): 结果有两个额外的捕获组 - 空白结果用于环顾四周,整个标记用外部{php ... php} ,但如果你使用PREG_PATTERN_ORDER你的预期结果将在第三个位置( [2] ) :

[2] => Array
(
    [0] => {php 1 php}
           {php 2 php}
           {php 3 php}
    [1] => 1
    [2] => 2
    [3] => 3
)

Here's a bit more complex example: http://ideone.com/sWWrT 这是一个更复杂的例子: http//ideone.com/sWWrT

Now, the mandatory word of caution. 现在,强制要求谨慎。 As I've said earlier, this is much more readable and maintainable with a simple depth counter, you don't really need a regex here, beyond recreational use. 正如我之前所说的,通过一个简单的深度计数器,它更具可读性和可维护性,除了娱乐用途之外,你真的不需要这里的正则表达式。

$regex = preg_match_all("/({php (\d+) php})+/", $content);
$regex[0][0] == "{php 1 php}";
$regex[0][1] == "{php 2 php}";
$regex[0][2] == "{php 3 php}";
end($regex)[0] == "1";
end($regex)[1] == "2";
end($regex)[2] == "3";

Looking for something like this? 正在寻找这样的东西?

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

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