Get content within a html tag using php and replace it after processing(使用php获取html标签中的内容并在处理后替换它)
问题描述
我有一个这样的 html (sample.html):
<头>头部><身体><div id="内容"><!--内容--><p>一些内容</p><!--内容-->
如何使用 php 获取位于 2 个 html 注释 '<!--content-->'
之间的内容部分?我想得到那个,做一些处理然后放回去,所以我必须得到和放!可能吗?
esafwan - 您可以使用正则表达式来提取 div(特定 id)之间的内容.
我之前为图片标签做过这件事,所以同样的规则也适用.我会查看代码并稍后更新消息.
[更新]试试这个:
]*'.$attr.'="'.$value.'">(.*?)<\/div>/si';preg_match($tag_regex,$xml,$匹配);返回 $matches[1];}$yourentirehtml = file_get_contents("test.html");$extract = get_tag('id', 'content', $yourentirehtml);回声 $extract;?>或者更简单:
preg_match("/]*id="content">(.*?)<\/div>/si", $text, $match);$content = $match[1];吉姆
I have an html (sample.html) like this:
<html>
<head>
</head>
<body>
<div id="content">
<!--content-->
<p>some content</p>
<!--content-->
</div>
</body>
</html>
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 - 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.
[update] try this:
<?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标签中的内容并在处理后替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用php获取html标签中的内容并在处理后替换它
基础教程推荐
猜你喜欢
-
Doctrine 2 - 在多对多关系中记录更改
2022-01-01
-
在 yii2 中迁移时出现异常“找不到驱动程序"
2022-01-01
-
如何在 Symfony 和 Doctrine 中实现多对多和一对多?
2022-01-01
-
在 CakePHP 2.0 中使用 Html Helper 时未定义的变量
2021-01-01
-
使用 PDO 转义列名
2021-01-01
-
如何在 XAMPP 上启用 mysqli?
2021-01-01
-
PHP 守护进程/worker 环境
2022-01-01
-
phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’"
2022-01-01
-
找不到类“AppHttpControllersDB",我也无法使用新模型
2022-01-01
-
HTTP 与 FTP 上传
2021-01-01