I am working on a program in which an addon needs to modify a system file.
I have a small method in which I am finding the beginning of the string in the file like this:
/**
* @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;
}
I am calling that from within the method where I need to pull that string out to replace it like this:
// Set our file to use
$originalFile = 'file.php';
// Find The array['key'] string
$myString = "\$array['key']";
// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);
Then echo $lineNo; returns $array['key'] = array(.
However, I need it to return the entire multi-line array/string up until the next ; (semicolon).
How would I go about this?
Thanks
* EDIT *
My PHP file contents are like this:
<?php
/**
* Comment here
*/
$first_array = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
'key4' => 'val4',
'key5' => 'val5'
);
$second_array = array(
'key1' => 'val1',
'key2' => 'val2'
);
...
I have tried the suggestion from @Scuzzy
This is in my method now:
// 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 );
}
}
}
However, this doesn't return anything.
I need to return something like:
$second_array = array(
'key1' => 'val1',
'key2' => 'val2'
);
As a string I can manipulate and rewrite.
is_array($token)... ;)