dsz7121 2015-10-23 23:53
浏览 227
已采纳

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

i have an html string with the following divs only:

<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>

I need to extract the inner text from divs "My title" etc.

how is it possible to do this with preg_match?

I tried the following (simple html dom) without luck:

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

Thanks !!!!

  • 写回答

3条回答 默认 最新

  • douruyun8153 2015-10-24 00:08
    关注
    preg_match('|<[^>]*title[^>]*>(.*?)<|', $html, $m);
    

    will give you "My Title".

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

    will give you "http//www.mpahmplakdjfe.co.uk/images/01.jpg".

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

    will give you "some text here".

    You can do it that way:

    $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'
    


    If you want to get all inner text from the string, use preg_match_all() instead of 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


    If you absolutely want inner texts only from <div>s, then you can modify preg_match_all() above like this:

    preg_match_all('|<div[^>]*>(?<innerText>[^<]+)<|', $html, $m);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记