【问题标题】:PHP special patternPHP 特殊模式
【发布时间】:2014-05-23 08:31:19
【问题描述】:

我正在使用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/ 对其进行测试时,它说没有找到模式。

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    使用双反斜杠\\ 引用$

    $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);
    

    【讨论】:

      【解决方案2】:

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

      $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&%$#@_ 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-27
        • 2012-11-25
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 2015-08-26
        • 2011-01-14
        相关资源
        最近更新 更多