正则表达式代码不会;t有效


A regex code doesn't works

我正在尝试使用正则表达式查找FINDTIS:bla-bla链接:<a href="http://www.exemple.net/index.php?p…

我的代码是:

$delimiter = '#';
$startTag = '<a href="http://www.exemple.net/index.php?p…'; // shortened
$endTag = '/1/">';
$regex = $delimiter . preg_quote($startTag, $delimiter) 
. '(.*?)' 
. preg_quote($endTag, $delimiter) 
. $delimiter 
. 's';
preg_match($regex,$result,$matches);
$category = $matches;
print_r($category);

但我什么也得不到。。。

问题出在哪里?谢谢

不确定我是否读对了这篇文章,但下面这样的内容与我认为你试图做的内容相当。注意,regex和html可能不会混合。但对于html文本块来说,这应该没问题。

当我想在标签中找到一个特定的att-val时,我倾向于采用前瞻性,将其定位在标签中的任何位置,并且足够安全,不会超过边界。

使用preg_match_all()作为示例。此处为测试用例http://ideone.com/oerbc
(固定的相对backref,应为-2)

$html = '
  <a href="http://www.exemple.net/index.php?p[some stuff to find]/1/">
  <a href=''http://www.exemple.net/index.php?p[more stuff to find]/1/ ''>
'; 
$ref_txtstart = 'http://www.exemple.net/index.php?p';
$ref_txtend   = '/1/';
$regex =
'~
<a 
  (?='s) 
  (?= (?:[^>"'']|"[^"]*"|''[^'']*'')*? (?<='s) href 's*=
      (?>
         's* ([''"]) 's*
         ' . preg_quote($ref_txtstart) . '
         (?<core>(?:(?!'g{-2}).)*)
         ' . preg_quote($ref_txtend) . '
         's* 'g{-2}
      )
  )
  's+ (?:".*?"|''.*?''|[^>]*?)+ 
>~xs
';
echo ("$regex'n");
preg_match_all( $regex, $html, $matches, PREG_SET_ORDER );
foreach ($matches as $val) {
   echo( "matched = $val[0]'ncore    = $val[core]'n'n"  );
}
?>

输出

~
<a 
  (?='s) 
  (?= (?:[^>"']|"[^"]*"|'[^']*')*? (?<='s) href 's*=
      (?>
         's* (['"]) 's*
         http'://www'.exemple'.net/index'.php'?p
         (?<core>(?:(?!'g{-2}).)*)
         /1/
         's* 'g{-2}
      )
  )
  's+ (?:".*?"|'.*?'|[^>]*?)+ 
>~xs
matched = <a href="http://www.exemple.net/index.php?p[some stuff to find]/1/">
core    = [some stuff to find]
matched = <a href='http://www.exemple.net/index.php?p[more stuff to find]/1/ '>
core    = [more stuff to find]

通过使用分支重置和
,可以将其扩展为包括未引用的值将命名的捕获缓冲区更改为所述捕获缓冲区的固定索引。

因此CCD_ 2变为CCD_ 3。示例在这里http://ideone.com/IHHLg

扩展正则表达式

$regex =
'~
<a 
  (?='s) 
  (?= (?:[^>"'']|"[^"]*"|''[^'']*'')*? (?<='s) href 's*=
    (?|
        (?>
           's* ([''"]) 's*
           ' . preg_quote($ref_txtstart) . ' ((?:(?!'g{-2}).)*) ' . preg_quote($ref_txtend) . '
           's* 'g{-2}
        )
      |
        (?> 
           (?!'s*[''"]) 's* ()
           ' . preg_quote($ref_txtstart) . ' ([^'s>]*) ' . preg_quote($ref_txtend) . '
           (?='s|>)
        )
    )
  )
  's+ (?:".*?"|''.*?''|[^>]*?)+ 
>~xs
';