【问题标题】:how to remove a string from a text file if the text contains a certain word如果文本包含某个单词,如何从文本文件中删除字符串
【发布时间】:2012-04-08 08:44:09
【问题描述】:

我正在尝试弄清楚如何删除文本文件之间的所有内容。

到目前为止,我有这个从文件中删除整个 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,但我只想删除其中一个 urlset,它是与某个变量匹配的那个,所以像这样(不起作用):

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

有谁知道我需要添加什么来删除目标 urlset,或者如果这看起来是解决问题的不好方法,甚至是更好的方法?

谢谢

【问题讨论】:

    标签: php xml file text


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常好用,包括 *?你添加了,谢谢 Flocsy
    猜你喜欢
    • 1970-01-01
    • 2014-08-11
    • 2012-06-24
    • 2022-01-17
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2020-10-13
    相关资源
    最近更新 更多