【问题标题】:Using PHP Regex or DOM, how to get web page's <TITLE>?</TITLE> with eol or newline in between the tags?使用 PHP Regex 或 DOM,如何在标签之间使用 eol 或换行符获取网页的 <TITLE>?</TITLE>?
【发布时间】:2019-01-20 21:40:39
【问题描述】:

我无法弄清楚如何从包含以下内容的 html 页面获取标题:

<title>Breaking <--- *EOL
- News</title>

*注意:在“Breaking”之后有一个不可见的 EOL 或换行符。

我已经尝试了几乎所有可能处理 eol 的正则表达式,但似乎没有任何效果。它总是什么都不返回。

preg_match('/\<title.*?\>(.*?)\<\/title\>/si', $str, $match);
preg_match('/(?s)\<title.*?\>(.*?)\<\/title\>/i', $str, $match)

$titles = $dom->getElementsByTagName('title');
$title = $titles->item(0)->nodeValue;

这个正则表达式在很多情况下都能正确抓取标题,但无论我尝试什么,标签之间的 eol 总是失败。

任何有意义的解决方案将不胜感激。

【问题讨论】:

  • DOM 方法有什么问题?在这里工作正常~eval.in/1047266
  • 您的第一个版本有效:ideone.com/s5u1wT
  • @Adriano 多行标志用于使^$ 匹配行的开头和结尾。 s 标志是他需要的,而且他已经拥有了。
  • @Barmar 我分叉了包含原始源代码的实际 html:ideone.com/67ICS3 它不起作用!
  • @dpark123 好吧,你的字符串有非转义引号。固定在这里~ideone.com/4ibFCT

标签: php html regex curl dom


【解决方案1】:

尝试检查并正常工作。

preg_match('/\<title\>(.*?)\<\/title\>/ism', $str, $match);
print_r($match[1]);

【讨论】:

  • 我已经检查过了,它工作正常。请检查@dpark123
【解决方案2】:

我写得真快

<?php
$title = '<title>Breaking
- News</title>';

preg_match('/<title[^>]*>(.*?)<\/title>/is', $title, $match);

echo $match[0]."\n";
echo $match[1]."\n";

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 2011-11-12
    相关资源
    最近更新 更多