在 PHP 文件中查找多行字符串

Finding multi-line string in PHP file

我正在开发一个插件需要修改系统文件的程序。

我有一个小方法可以在文件中找到字符串的开头,如下所示:

     /**
     * @param $fileName
     * @param $str
     *
     * @return int
     */
    private function getLineWithString($fileName, $str)
    {
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                return $line;
            }
        }
        return -1;
    }

我在方法中调用它,我需要将该字符串取出来替换它,如下所示:

//  Set our file to use
$originalFile = 'file.php';

// Find The array['key'] string
$myString = "$array['key']";

// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);

然后 echo $lineNo; returns $array['key'] = array(.

但是,我需要它 return 整个多行 array/string 直到下一个 ; (分号)。

我该怎么做?

谢谢

* 编辑 *

我的PHP文件内容是这样的:

<?php 
    /**
     * Comment here 
    */
     $first_array = array( 
         'key1' => 'val1', 
         'key2' => 'val2', 
         'key3' => 'val3', 
         'key4' => 'val4', 
         'key5' => 'val5' 
    );

    $second_array = array( 
        'key1' => 'val1', 
        'key2' => 'val2' 
    ); 
    ...

我试过@Scuzzy的建议

现在这是我的方法:

// Open Existing File And Get Contents
$myFile = file_get_contents('myFile.php');

$tokens = token_get_all($myFile);

foreach ( $tokens as $token ) {
    if (is_array($token)) {
        if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
        {
            var_dump( $token );
        }
    }
}

然而,这 return 什么都没有。

我需要 return 类似的东西:

$second_array = array( 
    'key1' => 'val1', 
    'key2' => 'val2' 
);

作为一个字符串,我可以操纵和重写。

我会研究 http://php.net/manual/en/function.token-get-all.php,尤其是 T_CONSTANT_ENCAPSED_STRING 中有换行符的

token.php

$code = file_get_contents('token.code.php');

$tokens = token_get_all( $code );

foreach ( $tokens as $token ) {
  if (is_array($token)) {
    if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
    {
      var_dump( $token );
    }
  }
}

token.code.php

<?php    
$bar = "single line";
$foo = "hello
multi
line
world";
$bar = 'single line';
$foo = 'hello
multi
line
world';

将打印多行而不是单行:

array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) ""hello
multi
line
world""
  [2]=>
  int(4)
}
array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) "'hello
multi
line
world'"
  [2]=>
  int(9)
}

与其尝试解析 PHP 中的 PHP 文件,不如根据您需要执行的操作,您可以使用 var_export().

require_once($filename);

// variables are now in global scope
// manipulate as necessary
$first_array['this_key'] = 'that value';

$str = '$first_array = '.var_export($first_array, TRUE).";\n\n";
$str .= '$second_array = '.var_export($second_array, TRUE).';';

// output the updated arrays back to the file
file_put_contents($filename, $str);