PHP使用正则表达式查找和删除字符串中的变量

With PHP, I'm opening a file and it looks like this:

var people = {
vikram: { time1: [ '8:00am', '8:20am', '8:40am', '9:00am',  ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am',  ], time3: [ '8:00am', '8:20am', '8:40am',  ], }};

The variable I'm trying to remove will contain a time (ex. 8:00am) and I will know the timeIndex(ex. time1). I also want to keep all the other times intact.

For example, if I set the variable to 8:40am, I want the new file that is being created to look like this:

var people = {
vikram: { time1: [ '8:00am', '8:20am', '9:00am',  ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am',  ], time3: [ '8:00am', '8:20am', '8:40am',  ], }};

Any help would be appreciated!

you can use preg_replace() for this:

<?php
$filename = 'yourfile.js';
$search = '8:40am';

$content = file_get_contents( $filename );

$pattern = '/(\s*time1:\s*\[.*)([\'"]' . 
           preg_quote($search) .
           '[\'"],?\s*)(.*\])/U';

$content = preg_replace( $pattern, '\1\3', $content ); 

file_put_contents( $filename, $content );
?>

This is a modification of the code example i answered to your last question on a similar topic.

The format you show represents a JSON formatted string. You can use json_decode() function to make an array from string, then loop through the array and just unset() the element you don't need.

Here is the way I did it. Basically, I use json_decode to parse your json to php object. However, I also found that your input is not a well-formed json for php (See example 3). Although my code doesn't look good and generic, but I hope it will help you.

<?php
$json_data = '{
    "vikram": {
        "time1": ["8:00am", "8:20am", "8:40am", "9:00am"], 
        "time2": ["10:20am", "10:40am", "11:00am", "11:20am"], 
        "time3": ["8:00am", "8:20am", "8:40am"]
    }
}';


$obj = json_decode($json_data);

//var_dump($obj->vikram);

$value = "8:40am";
$time1 = "time1";

$delete_item;

foreach($obj->vikram as $name=>$node)
{
    foreach($node as $i => $time)
    {
        if($time==$value && $name=$time1)
        {
            $delete_item = $i;
        }
    }
}

unset($obj->vikram->time1[$delete_item]);
var_dump($obj->vikram);