使用 html 字符串按 id 从 div 中提取内部文本

Extract inner text from a div by id using an html string

我有一个 html 字符串,仅包含以下 div:

<div id="title">My Title</div>
<div id="image">http://www.mpahmplakdjfe.co.uk/images/01.jpg</div>
<div id="fullcontent">In this div there are some html elements more</div>

我需要从div中提取内部文本"My title"等

如何用 preg_match 做到这一点?

我尝试了以下(简单 html dom)但没有成功:

$html = new simple_html_dom();
$html->load_file($myhtml);
$ret = $html->find('div[id=title]')->innertext; (or outter) 
echo $ret;

谢谢!!!!

    $subject = "<div id=\"image\">http://www.mpahmplakdjfe.co.uk/images/01.jpg</div>";

    preg_match("/<div id=\".*\">(.*)<\/div>/", $subject, $matches);

    print_r($matches[1]);

要更详细地了解所使用的正则表达式:

https://regex101.com/r/tN6mD8/1

正则表达式在 PHP 中看起来有点混乱,因为必须转义双引号。我总是先在单独的编辑器中写我的。

编辑:获取特定标签:

    $subject = '<div id="image">http://www.mpahmplakdjfe.co.uk/images/01.jpg</div>';
    $title = '"image"';

    preg_match("/<div id=".$title.">(.*)<\/div>/", $subject, $matches);
preg_match('|<[^>]*title[^>]*>(.*?)<|', $html, $m);

会给你"My Title".

preg_match('|<[^>]*image[^>]*>(.*?)<|', $html, $m);

会给你"http//www.mpahmplakdjfe.co.uk/images/01.jpg".

preg_match('|<[^>]*fullcontent[^>]*>(.*?)<|', $html, $m);

会给你"some text here".

你可以这样做:

$html = '<div id="title">My Title</div>
<div id="image">http://www.mpahmplakdjfe.co.uk/images/01.jpg</div>
<div id="fullcontent">some text here</div>';

$m = array();
preg_match('|<[^>]*title[^>]*>(.*?)<|', $html, $m);
// inner text is in $m[1]
echo $m[1]; // == 'My Title'


如果要从字符串中获取所有内部文本,请使用 preg_match_all() 而不是 preg_match():

// say you have that string
$html = '<div id="fullcontent"><div>hi</div><div>hello</div></div>';

$m = array();
preg_match_all('|>(?<innerText>[^<]*)<|', $html, $m);
echo count($m['innerText']); // 2     ;how many matches
echo $m['innerText'][0];     // == 'hi'
echo $m['innerText'][1];     // == 'hello'

phpfiddle - http://x.co/6lbC6


如果你绝对只想要来自 <div>s 的内部文本,那么你可以像这样修改上面的 preg_match_all()

preg_match_all('|<div[^>]*>(?<innerText>[^<]+)<|', $html, $m);

我有同样的问题,我通过使用正则表达式找到了解决方案。 Here is the answer 你的情况:

\<div.*?\>(.*?)<\/div>