如果文本包含某个单词,如何从文本文件中删除字符串

时间:2012-04-08 08:44:10

标签: php xml file text

我试图找出如何删除文本文件之间的所有内容。

到目前为止,我有这个从文件中删除整个urlset。

$myFile = "/here/it/is/sitemap.xml"; 

$stringdata = file_get_contents($myFile);

$stringdata = preg_replace('#(<urlset.*?>).*?(</urlset>)#', '$1$2', $stringdata);

$stringdata = str_replace('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"></urlset>', '', $stringdata);

$fh = fopen($myFile, 'w') or die("can't open file");

fwrite($fh, $stringdata);
fclose($fh);

return;

问题是我在文本文件中有几个urlset但我只想删除其中一个urlsets,这是匹配某个变量的那个,所以像这样(这不起作用):

$stringdata = preg_replace('#(<urlset.*?>).*? . $thisvariableisintheurlset . (</urlset>)#', '$1$2', $stringdata);

有没有人知道我需要添加什么来删除目标urlset,或者更好的方法,如果这看起来像是一种解决问题的坏方法?

由于

1 个答案:

答案 0 :(得分:1)

尝试使用http://php.net/manual/en/function.preg-quote.php

$stringdata = preg_replace('#(<urlset.*?>).*?' . preg_quote($thisvariableisintheurlset, '#') . '.*?(</urlset>)#', '$1$2', $stringdata);

还要确保引用变量之前和之后的内容匹配(我添加。* ?,但这可能不适合您的情况)

相关问题