从使用PHP文件系统

时间:2018-06-17 14:34:18

标签: php regex xml preg-replace

我有一个使用PHP file_get_contents读取的XML文件,因此可以对其进行其他更改。

我需要找到并删除整个文件中的节点<BATCHALLOCATIONS.LIST> ... <BATCHALLOCATIONS.LIST>(不仅仅是那两行,而是整个节点之间的内容)。

由于文件已经使用file_get_contents加载,我希望这样做而不必使用simpleXML或XML解析器或任何其他方法(如DOM)再次加载文件

该节点没有特定的父节点,并且随机出现。

XML文件从Business Accounting Software导出。

有关如何实现这一目标的任何想法?也许使用正则表达式进行搜索和替换或类似的东西?

我一直在尝试使用正则表达式和preg_replace来做这件事,但只是无法让事情发挥作用。

Here's just a portion of the file。原版运行到10K +行。

这应该有效,但不是

preg_replace('/^\<BATCHALLOCATIONS.LIST\>(.*?)\<\BATCHALLOCATIONS.LIST\>$/ism','', $newXML);

我试图在不使用任何HTML / XML解析器的情况下执行此操作。

1 个答案:

答案 0 :(得分:-1)

可能有更好的方法,但这会有效

// get your file as a string 
$yourXML = file_get_contents($file) ;

$posStart = stripos($yourXML,'<BATCHALLOCATIONS.LIST>') ;
$posEnd = stripos($yourXML,'</BATCHALLOCATIONS.LIST>') + strlen('</BATCHALLOCATIONS.LIST>') ;

$newXML = substr($yourXML,0,$posStart) . substr($yourXML,$posEnd) ;