繁体   English   中英

如何使用PHP从HTML源代码中提取特定字符串

[英]How to Extract Particular String from the HTML Source code using PHP

我正在尝试从整个HTML源代码中提取特定的字符串。

HTML来源:查看来源: https://www.instagram.com/p/BUbZXXMjnxY/?taken-by=narentrigger&hl=enhttps://www.instagram.com/p/BUbZXXMjnxY/?taken-by=narentrigger&hl=en -by https://www.instagram.com/p/BUbZXXMjnxY/?taken-by=narentrigger&hl=en - https://www.instagram.com/p/BUbZXXMjnxY/?taken-by=narentrigger&hl=en

需要提取字符串: https://instagram.fmaa1-2.fna.fbcdn.net/t51.2885-15/e35/18645014_163619900839441_7821159798480568320_n.jpg : https://instagram.fmaa1-2.fna.fbcdn.net/t51.2885-15/e35/18645014_163619900839441_7821159798480568320_n.jpg来自“ og:image”元属性。

我尝试了一些方法,但是一切都出错了。 有什么方法可以从源代码的og:image meta属性中获取图像链接。 提取后需要将图像URL存储在特定变量上。 需要专家帮助。 需要提取的网址

如果仅获取一个子字符串,请不要使用preg_match_all() 加载DOMDocument似乎对于此任务来说是过大的。

通过使用\\K ,可以减少结果数组的膨胀。

输入样例:

$input='<meta property="og:title" content="Instagram post by Narendiran blah blah" />
<meta property="og:image" content="https://instagram.fmma1-2.blah.jpg" />
<meta property="og:description" content="8 Likes, 1 Comments - blah" />';

方法( 演示 ):

$url=preg_match('/"og:image"[^"]+"\K[^"]+/',$input,$out)?$out[0]:null;
echo $url;

输出:

https://instagram.fmma1-2.blah.jpg

通过使用否定的字符类,正则表达式引擎将更有效地运行。 [^"] 。( 模式演示

假设您在PHP的字符串中包含标记,那么RegEx什么问题

preg_match_all('/<meta.*property="og:image".*content="(.*)".*\/>/', $string, $matches);
echo $matches[1][0];

演示版

免责声明:可能会提供更有效的正则表达式

在此代码段中,我使用DOMDocument从meta标记中抓取属性内容。 它将存储在数组中以防万一并返回。 希望它能工作。

   function get_img_url($url) { 

        // Create a new DOM object 
        $html = new DOMDocument(); 

        // load the HTML page 
        $html->loadHTMLFile($url); 

        // create a empty array object 
        $imageArray = array(); 

        //Loop through each meta tag
        foreach($html->getElementsByTagName('meta') as $meta) { 
            $imageArray[] = array('url' => $meta->getAttribute('content')); 
        } 

        //Return the list 
        return $imageArray; 
    } 

尝试使用此代码来抓取网页。 我使用了simple_html_dom_parser 您可以从https://sourceforge.net/projects/simplehtmldom/files/下载

include_once("simple_html_dom.php");

$output_filename = "example_homepage.html";
$fp = fopen($output_filename, 'w');
$url = 'https://www.instagram.com/p/BUbZXXMjnxY/?taken-by=narentrigger&hl=en';
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_FILE, $fp);
$result = curl_exec($curl);

curl_close($curl);
fclose($fp);

$html = file_get_html('example_homepage.html');

foreach($html->find('meta[property=og:image]') as $element) 
   echo $element->content . '<br>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM