使用php在html标签中获取内容,并在处理后将其替换 [英] Get content within a html tag using php and replace it after processing

查看:534
本文介绍了使用php在html标签中获取内容,并在处理后将其替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html(sample.html),如下所示:

I have an html (sample.html) like this:

<html>
<head>
</head>
<body>
<div id="content">
<!--content-->

<p>some content</p>

<!--content-->
</div>
</body>
</html>

如何获取2个html注释之间的内容部分<! - content - >'使用php?我想弄明白,做一些处理并把它放回去,所以我必须得到并放下!是否有可能?

How do i get the content part that is between the 2 html comment '<!--content-->' using php? I want to get that, do some processing and place it back, so i have to get and put! Is it possible?

推荐答案

esafwan - 您可以使用正则表达式来提取div(某个id) 。

esafwan - you could use a regex expression to extract the content between the div (of a certain id).

之前我已经为图片标签完成了这项工作,所以应用了相同的规则。

I've done this for image tags before, so the same rules apply. i'll look out the code and update the message in a bit.

[更新] 试试这个:

<?php
    function get_tag( $attr, $value, $xml ) {

        $attr = preg_quote($attr);
        $value = preg_quote($value);

        $tag_regex = '/<div[^>]*'.$attr.'="'.$value.'">(.*?)<\\/div>/si';

        preg_match($tag_regex,
        $xml,
        $matches);
        return $matches[1];
    }

    $yourentirehtml = file_get_contents("test.html");
    $extract = get_tag('id', 'content', $yourentirehtml);
    echo $extract;
?>

或更简单:

or more simply:

preg_match("/<div[^>]*id=\"content\">(.*?)<\\/div>/si", $text, $match);
$content = $match[1]; 

jim

这篇关于使用php在html标签中获取内容,并在处理后将其替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆