如果文本包含某个单词,如何从文本文件中删除字符串
I am trying to figure out how to remove everything between and including in a text file.
So far I have this that removes a whole urlset from a file.
$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;
The problem is I have several urlsets in the text file but I only want one of the urlsets to be removed, which is the one that matches a certain variable, so something like this (which doesn't work) :
$stringdata = preg_replace('#(<urlset.*?>).*? . $thisvariableisintheurlset . (</urlset>)#', '$1$2', $stringdata);
Does anyone know what I need to add to this to remove the targeted urlset, or even a better way if this looks like a bad way to attack the problem?
Thanks
我试图找出如何删除文本文件之间的所有内容。 p>
到目前为止,我有一个从文件中删除整个urlset。 p>
$ myFile =“/ where / it / is / sitemap”;
$ stringdata = file_get_contents($ myFile);
$ stringdata = preg_replace('#(&lt; urlset。*?&gt;)。*?(&lt; / urlset&gt;)#','$ 1 $ 2 ',$ stringdata);
$ stringdata = str_replace('&lt; urlset xmlns =“http://www.sitemaps.org/schemas/sitemap/0.9”xmlns:video =“http://www.google .com / schemas / sitemap-video / 1.1“&gt;&lt; / urlset&gt;','',$ stringdata);
$ fh = fopen($ myFile,'w')或die(”不能 打开文件“);
fwrite($ fh,$ stringdata);
nclclose($ fh);
return;
code> pre>
问题是我 在文本文件中有几个urlset,但我只想删除其中一个urlsets,这是一个匹配某个变量的urlsets,所以这样的东西(不起作用): p>
$ stringdata = preg_replace('#(&lt; urlset。*?&gt;)。*?。$ thisvariableisintheurlset。(&lt; / urlset&gt;)#','$ 1 $ 2',$ stringdata);
code> pre>
有没有人知道我需要添加什么来删除目标urlset,或者更好的方法,如果这看起来像是一种不好的方法来解决问题? p>
感谢 p>
div>
try to use http://php.net/manual/en/function.preg-quote.php
$stringdata = preg_replace('#(<urlset.*?>).*?' . preg_quote($thisvariableisintheurlset, '#') . '.*?(</urlset>)#', '$1$2', $stringdata);
also make sure that the things before and after the quoted variable are matched (I added .*?, but that might be not correct for your case)