dongqiyang3711 2012-04-08 08:44 采纳率: 100%
浏览 271
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dragon7088 2012-04-08 08:48
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改