dongtidai6519 2014-11-07 19:07
浏览 124
已采纳

如何让preg_replace()删除两个标签之间的文本?

I'm trying to make a function in PHP that can delete code within two tags from all .js file within one folder and all its subfolders. So far everything works except preg_replace(). This is my code:

<?php

deleteRealtimeTester('test');

function deleteRealtimeTester($folder_path)
{
    foreach (glob($folder_path . '/*.js') as $file) 
    {
        $string = file_get_contents($file); 

        $string = preg_replace('#//RealtimeTesterStart(.*?)//RealtimeTesterEnd#', 'test2', $string);

        $file_open = fopen($file, 'wb');
        fwrite($file_open, $string);
        fclose($file_open);
    }

    $subfolders = array_filter(glob($folder_path . '/*'), 'is_dir');

    if (sizeof($subfolders) > 0)
    {
        for ($i = 0; $i < sizeof($subfolders); $i++)
        {
            echo $subfolders[$i];
            deleteRealtimeTester($subfolders[$i]);
        }
    }
    else
    {
        return;
    }
}

?>

As mentioned I want to delete everything inside these tags and the tags themselve:

//RealtimeTesterStart

//RealtimeTesterEnd

It is important that the tags contains the forward slashes and also that if a file contains multiple of these tags, only code from //RealtimeTesterStart to //RealtimeTesterEnd is deleted and not from //RealtimeTesterEnd to //RealtimeTesterStart.

I hope that someone can help me.

  • 写回答

2条回答 默认 最新

  • dongtou2016 2014-11-07 19:13
    关注

    I'm assuming that //RealtimeTesterStart, //RealtimeTesterEnd and the code in between are on different lines? In PCRE . does NOT match newlines. You need to use the s modifier ( and you don't need the () unless you need the captured text for the replacement):

    #//RealtimeTesterStart.*?//RealtimeTesterEnd#s
    

    Also, look at GLOB_ONLYDIR for glob instead of array_filter. Also, also, maybe file_put_contents instead of fopen etc.

    Maybe something like:

    foreach (glob($folder_path . '/*.js') as $file) {
        $string = file_get_contents($file);
        $string = preg_replace('#//RealtimeTesterStart.*?//RealtimeTesterEnd#s', 'test2', $string);
        file_put_contents($file, $string);
    }
    
    foreach(glob($folder_path . '/*', GLOB_ONLYDIR) as $subfolder) {
        deleteRealtimeTester($subfolder);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?