【问题标题】:preg_match won't return the row but detects it (PHP)preg_match 不会返回该行但会检测到它(PHP)
【发布时间】:2015-06-20 15:13:21
【问题描述】:

这是我的代码:

            $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://comic.naver.com/webtoon/detail.nhn?titleId=570506&no=99&weekday=thu");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1");
        $result = curl_exec($ch);
        curl_close($ch);

 $matches = array();
        preg_match('/^.*\bcontent_image_0\b.*$/um', $result, $matches, PREG_OFFSET_CAPTURE);

var_dump($matches); 

我最后加了/um,因为网站上的字符集是UTF-8。

我想要它做的是找到包含“content_image_0”的行并返回整行。

这就是 var_dump($matches);转储:

array(1) { [0]=> array(2) { [0]=> string(383) "   " [1]=> int(25958) } }

我们可以看到它检测到383个字符串但没有返回它们,引号是空的:/

【问题讨论】:

  • 模式很好,但您看不到结果,因为浏览器中没有出现 html 标签。所以右键单击并显示页面源。或者使用echo htmlspecialchars($matches[0][0]);在浏览器中显示字符串,或者echo htmlspecialchars(print_r($matches, true));
  • 啊,谢谢你的回答,哈哈。

标签: php regex preg-match


【解决方案1】:

你必须像这样使用捕获组:

preg_match('/^(.*\bcontent_image_0\b.*)$/um', $result, $matches, PREG_OFFSET_CAPTURE);
              ^---      here       ---^

【讨论】:

    【解决方案2】:

    要捕获一个匹配项(与整个匹配项不同),您需要使用一个捕获组,由括号() 表示,围绕您要捕获的数据。例如,要捕获整行:

    preg_match('/^(.*\bcontent_image_0\b.*)$/um', $result, $matches, PREG_OFFSET_CAPTURE);
    

    要捕获并返回所有 383 个匹配的行/行,您需要使用 preg_match_all() 每行一个捕获组,您可以执行以下操作:

    preg_match_all('/^(.*\bcontent_image_0\b.*)$/um', $result, $matches, PREG_OFFSET_CAPTURE);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多