php正则替换,为什么多出</html>?运行test.php,得到的结果是
<body>
hello
</body>
</html>
为什么多出</html>?test.html的代码如下<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- Source is http://www.ccw.com.cn/ -->
<head>
</head>
<body>
hello
</body>
</html>
test.php代码如下<?php
$file=file_get_contents("test.htm");
$file=preg_replace("#.*(<body[^>]*>.*</body>).*#isU","$1",$file);
echo $file;
?>

解决方案 »

  1.   

    最后的.*出问题了,它可以不匹配任何东西,所以就把</html>给留下来了
    在正则的最后加一个结束符$,应该就能解决问题了,匹配到结尾
    试试看
      

  2.   


    <?php
        $file=file_get_contents("test.htm");
        $file=preg_replace("#.*(<body[^>]*>.*$</body>).*#isU","$1",$file);
        echo $file;
    ?>
      

  3.   


    <?php
        $html=file_get_contents("test.html");
        preg_match('{<body(.*)</body>}is', $html, $body);
    print_r($body[0]);
    ?>
      

  4.   

    $file=file_get_contents("test.html");
    preg_match('#(<body[^>]*>.*</body>)#isU', $file, $arr);
    $file = $arr[1];echo $file;
      

  5.   

        $file=preg_replace("#.*(<body[^>]*>.*</body>).*#is","$1",$file);
        echo $file;<body>
    hello
    </body>