[英]extract some html with preg_match
我以任何方式使用preg_mach提取一些html(我尝试使用DOMDocument,但换行时遇到了一些问题)...这就是我的代码..
1.html
<body>
<!-- icon and title -->
<div class="smallfont">
<img class="inlineimg" src="images/icons/icon1.gif" alt="" border="0" />
<strong>qrtoobah 3nwan</strong>
</div>
<hr size="1" style="color:#CCCCCC; background-color:#CCCCCC" />
<!-- / icon and title -->
<div id="post_message_14142536">
<font size="7"><font color="red">msaha 700</font></font><br />
<font size="7"><font color="red">shamali 20</font></font><br />
<font size="7"><font color="red"> 1700 almetr</font></font><br />
<font size="7"><font color="#ff0000">sooom bs</font></font><br />
<font size="7"><font color="#ff0000">albee3 qreeb</font></font>
</div>
<!-- message -->
</body>
extract.php
<?php
$html = file_get_contents("1.html");
$pattern = '/<([!]+)([^]+).*>([^]+)(message\ \-\-\>)/';
preg_match($pattern, $html, $matches);
print_r($matches);
?>
我想在<!-- icon and title -->)blablabla(<!-- / message -->
之间得到任何东西<!-- icon and title -->)blablabla(<!-- / message -->
...但是我得到那个数组:
Array ( [0] => [1] => ! [2] => -- [3] => message --> )
使用strpos
查找第一个标签的位置。 然后使用strpos
查找结尾标记。 我的意思是-如果您知道从哪里到您要找的东西,它们是唯一的..那么preg_*
函数又有什么用呢?
所以我想这样的事情会很好地工作(为了使我的想法一步一步地执行,我将代码尽可能地清楚了):
$tag_begin = "<!-- icon and title -->";
$tag_end = "<!-- message -->";
$begin = strpos($tag_begin,$text)+strlen($tag_begin);
$end = strpos($tag_end,$text);
$result = substr($begin,$end, $text);
如果您想查找并存储打开<!-- (.*) -->
和关闭<!-- / (.*) -->
之间的所有结构,也可以完全相同。
只需要更改u-首先使用preg_match查找所有开放结构的名称。 例如:
$result_cnt = preg_match_all('#<!-- [^/].*-->#', $text , $openings);
// Output for your example HTML is:
$openings =
array (
0 =>
array (
0 => '<!-- icon and title -->',
1 => '<!-- message -->',
),
)
之后,在$ openings的一个循环中查找上面所有需要的代码。 只是添加到在正确位置关闭“ /”字符的开口处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.