我想创建一个PHP程序,它可以创建一个可以读取这个文件的.php文件:
<html>
<head>
<title> Hello World! </title>
</head>
<body>
</body>
</html>它将搜索包含中间标签的<head>和</head>标签,并将选择的标签传输到header.php
因此,header.php将具有以下内容:
<head>
<title> Hello World! </title>
</head>另一个问题是,如何在页面的开头插入PHP标记<?php,并在文件的最后插入?>。
我已经在这里完成了这段代码,但它还没有完成,而且我不读取<head>标记。
<?php
firstIdentifier = '<head>';
$secondIdentifier = '</head>';
$currentContent = str_replace("\n", "", file_get_contents('sourcefile.txt'));
$pattern = '/('.$firstIdentifier.')(.+?)('.$secondIdentifier.')/';
//get all text between the two identifiers, and include the identifiers in the match result
preg_match_all($pattern, $currentContent , $matches);
//stick them together with space delimiter
$contentOfNewFile = implode(" ",$matches[0]);
//save to a new file
$newFile = fopen('destinationFile.txt','a');
fwrite($newFile, $contentOfNewFile);
?>请帮帮我。
发布于 2010-11-17 14:11:18
我觉得你做得太难了。您是否考虑过使用SimpleXML库将HTML解析为可扩展标记语言?你可以做到的!请允许我解释一下:
假设您将文件读入一个名为$html_main的字符串变量,现在考虑以下代码:
$dom = new DOMDocument("1.0", "UTF-8");
$dom->loadHTML($html_main);
$xml = simplexml_import_dom($dom);使用XPATH (//html/head)将给出节点,只需调用函数:
$xpathObj = $xml->xpath('//html/head');然后你就可以把HTML代码作为一个集合来管理了!我认为,如果您计划进行一些主要的解析,那么这可能是一个更好的方法!
https://stackoverflow.com/questions/4201600
复制相似问题