2012-04-19 65 views
0

我怎样才能既(http://[^"]+)的?:匹配 有没有办法匹配递归/嵌套正则表达式? (PHP,preg_match_all)

<a href="http://yoursite.com/goto/http://aredirectURL.com/extraqueries"></a> 

(我知道这是非法URL,但同样的想法)

我想正则表达式给我这两比赛:

1 http://yoursite.com/goto/http://aredirectURL.com/extraqueries 
2 http://aredirectURL.com/extraqueries 

无运行多个preg_match_all的

真的难住了,为感谢任何光线都可以流下。

+0

任意嵌套,或最多两个? (前者是不可能的,只有一个PHP正则表达式。) – Ryan 2012-04-19 23:05:15

+2

@minitech [递归正则表达式man!](http://stackoverflow.com/a/3180176/31671):P – alex 2012-04-19 23:15:32

+1

@alex:呃...哇。 – Ryan 2012-04-19 23:17:29

回答

1

这个正则表达式会得到你想要的输出:((?:http://[^"]+)(http://[^"]+))。请注意非捕获组(?:regex)的使用情况。要阅读有关非捕获组的更多信息,请参见Regular Expression Advanced Syntax Reference

<?php 
preg_match_all(
    '((?:http://[^"]+)(http://[^"]+))', 
    '<a href="http://yoursite.com/goto/http://aredirectURL.com/extraqueries"></a>', 
    $out); 
echo "<pre>"; 
print_r($out); 
echo "</pre>"; 
?> 

上述代码输出以下:

Array 
(
    [0] => Array 
     (
      [0] => http://yoursite.com/goto/http://aredirectURL.com/extraqueries 
     ) 

    [1] => Array 
     (
      [0] => http://aredirectURL.com/extraqueries 
     ) 

) 
+0

完美,谢谢!这个是我最终做的:'/((?: http [^ \“\'\ s>] +)?(http [^ \”\'\ s>] +))/ gism' – tweak2 2012-04-19 23:50:43

0

可以在该功能分割字符串:

http://de.php.net/preg_split

每个部分可以包含例如结果中给出的数组中的一个网址。

如果有更多的内容,可以在全文“工作”的时候使用回调操作调用preg_split。

0
$str = '<a href="http://yoursite.com/goto/http://aredirectURL.com/extraqueries"></a>'; 

preg_match("/\"(http:\/\/.*?)(http:\/\/.*?)\"/i", $str, $match); 

echo "{$match[0]}{$match[1]}\n"; 
echo "{$match[1]}\n";