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!

使用PHP,我打开一个文件,它看起来像这样: p> var people = { vikram:{time1:['上午8:00','上午8:20','上午8:40','上午9:00',],时间2:['10:20am' ,'10:40am','11:00am','11:20am',],time3:['上午8:00','上午8:20','上午8:40',],}}; pre>

我想要删除的变量将包含一个时间(例如上午8:00),我将知道timeIndex(例如time1)。 我还希望保持所有其他时间不变。 p>

例如,如果我将变量设置为上午8:40,我希望创建的新文件看起来像这样: / p>

  var people = {
vikram:{time1:['8:00 am','8:20 am','9:00 am',],time2:['10: 上午20点,'10:40:00','11:00am','11:20am',],时间3:['上午8:00','上午8:20','上午8:40',],}}; \  n  code>  pre> 
 
 

任何帮助将不胜感激! p> div>

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);