【问题标题】:preg_match get textpreg_match 获取文本
【发布时间】:2013-04-08 15:22:03
【问题描述】:

我有 test.php 和 test1.php 我有这个 php 代码正在运行

<?php 
$Text=file_get_contents("http://inviatapenet.gethost.ro/sop/test.php");
 preg_match_all('~fid="(.*?)"~si',$Text,$Match);
 $fid=$Match[1][1];
 echo $fid;
?>

我想做的是从 test.php 中获取文本

从这个 fid='gty5etrf' JavaScript 我只需要 fid 的内容

<script type='text/javascript'>fid='gty5etrf'; v_width=620; v_height=490;</script><script type='text/javascript' src='http://www.reyhq.com/player.js'></script>

在 test1.php 中我只需要显示内容

gty5etrf

我要做什么?

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    一个简短的模式:

    $pattern = '~\bfid\s*=\s*["\']\K\w+~';
    

    或长模式:

    $pattern = '~<script[^>]*>(?:[^f<]+|\Bf+|f(?!id\b)|<+(?!/script>))*+\bfid\s*=\s*(["\'])\K[^"\']+(?=\1)~';
    

    结果

    preg_match($pattern, $Text, $match);
    $fid = $match[0];
    

    短模式查找如下序列:

    fid='somechars
    fid  = "somecchars
    

    长模式的作用相同,但也会检查您是否在脚本标签之间。


    使用 XPath:

    $html = <<<'EOD'
    <script type='text/javascript'>fid='gty5etrf'; v_width=620; v_height=490;</script><script type='text/javascript' src='http://www.reyhq.com/player.js'></script>
    EOD;
    
    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    $xp = new DOMXPath($dom);
    $query = <<<'EOD'
        substring-before(
            substring-after(
                //script[contains(., "fid='")],
                "fid='"
            ),
            "'"
        )
    EOD;
    
    echo $xp->evaluate($query);
    

    【讨论】:

      【解决方案2】:
       preg_match_all('/fid=\'([^\']+)\'/',$Text,$Match);
      

      您的正则表达式错误。 首先,您正在寻找fid="..." 而不是fid='...'。 其次,对于.*,正则表达式将匹配比fid 属性结尾更远的任何字符。

      这里是完整的代码:

      preg_match_all('/fid=\'([^\']+)\'/',$Text,$Match);
      $fid=$Match[1][0];
      echo $fid;
      

      【讨论】:

      • 他使用的是.*?,而不是.*。 ? 使它不贪婪。
      • 在这种情况下,我看不出.* 和.*? 之间的区别。
      • 如果输入是fid='foo' other='bar','.*' 将匹配'foo' other='bar',因为它是贪婪的,但'.*?' 将仅匹配'foo',因为它是非贪婪的。
      • 不,因为我使用的是[^\'],所以正则表达式不会比遇到的第一个' 读得更远。 @PortaltvRomania:我试过了,它对我有用......
      【解决方案3】:

      您可以尝试表达式 fid\=\'([^\']+)\',因为 [^\']+ 以正确的方式使表达式非贪婪,而且该表达式是错误的,因为它正在寻找双引号而不是单引号。

      【讨论】:

      • .*? 已经是非贪婪的,这就是 ? 修饰符的用途。
      【解决方案4】:

      '' 内的匹配字符串:'(?:[^\\']*|\\.)*'

      "" 内的匹配字符串:"(?:[^\\"]*|\\.)*"

      两者(忽略空格):fid\s*=\s*('(?:[^\\']*|\\.)*'|"(?:[^\\"]*|\\.)*")

      并为 php 转义:

      $regexp = '~fid\\s*=\\s*(\'(?:[^\\\\\']*|\\\\.)*\'|"(?:[^\\\\"]*|\\\\.)*")~';
      

      即使这样也能正确处理:

      fid  = 'foo\'s bar';
      

      【讨论】:

        【解决方案5】:

        这应该是

        $fid=$Match[1][0];
        

        而不是:

        $fid=$Match[1][1];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-17
          • 1970-01-01
          • 2013-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多