PHP特殊模式

时间:2014-05-23 08:31:20

标签: php html regex

我正在使用preg_match_all()来从HTML文件中提取所有密钥字符串。 每个键字符串都在_@#$%&KEY_NAME&%$#@_之类的模式中。

所以我有:

$html = file_get_contents("htmlFile.html");
if ($html){
  $matches = null;
  $keys = preg_match_all("/(_@#\$%&)(?P<key>\w+)(&%\$#@_)/", $html, $matches, PREG_SET_ORDER);
  if (($keys >= 0)&&($keys != false)){
     if ($keys == 0)
       echo "preg_match_all() returns 0";
     else{
        foreach($matches as $val)
           echo $val[key];
     }
  }
}

HTML文件内容:

<label for="button_ok">_@#$%&LABEL_BUTTON_OK&%$#@_</label>
<input type="button" value="_@#$%&TEXT_BUTTON_OK&%$#@_" />

http://tryphpregex.com/进行测试时,它表示没有找到模式。

2 个答案:

答案 0 :(得分:0)

使用双反斜\\引用$

$html = '<label for="button_ok">_@#$%&LABEL_BUTTON_OK&%$#@_</label>
<input type="button" value="_@#$%&TEXT_BUTTON_OK&%$#@_" />';
preg_match_all("/(_@#\\$%&)(?P<key>\w+)(&%\\$#@_)/", $html, $matches, PREG_SET_ORDER);
print_r($matches);

答案 1 :(得分:0)

尝试使用('')单引号来匹配字符串

$html = '<label for="button_ok">_@#$%&LABEL_BUTTON_OK&%$#@_</label>
<input type="button" value="_@#$%&TEXT_BUTTON_OK&%$#@_" />';
preg_match_all('/(_@#\$%&)(?P<key>\w+)(&%\$#@_)/', $html, $matches, PREG_SET_ORDER);
//print_r($matches);
echo $matches[0][0]; //_@#$%&LABEL_BUTTON_OK&%$#@_
echo $matches[1][0]; //_@#$%&TEXT_BUTTON_OK&%$#@_