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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算