tags:

views:

103

answers:

2

I have a php file that can read the contents of other files perfectly and return them as a string.

$contents = $file->read(); // return as string.

i need to be able to search and replace certain lines

lines that begin with $this->Session->setFlash and end with , true)); must be replaced with

lines that begin with $this->Session->setFlash and end with , true), 'default', array('class'=>'flash_failure'));

I have grep in my machine, if that helps.

finally after the contents is changed, i have a function that will write the contents back

$file->write($contents);

I know this helps to find the lines, but I have no idea how to replace.

^.*Session->setFlash.*, true\)\);$
+1  A: 

You can try:

$contents = $file->read(); // return as string.

// change contents.
$contents = preg_replace('/^(\$this->Session->setFlash.*?), true\)\);$/',"$1, true), 'default', array('class'=>'flash_failure'));",$contents);

$file->write($contents);
codaddict
your code is working but somehow it does not work on the $contents when i do a $contents= file_get_contents($filename); your code works because i tested here at http://codepad.viper-7.com/V3BS6H
keisimone
What exactly do you mean by `does not work`? Try printing the value of `$contents` after you get it using `file_get_contents`
codaddict
there are multiple lines inside the file. so i suspect i need to set a /m modifier. but i stll cannot get it to work. see this for more details. http://codepad.viper-7.com/1twh2k
keisimone
A: 

the solution is thus:

$contents = preg_replace('/^(.*Session->setFlash.*, true\))\);$/m',
                                         "$1, 'default', array('class'=>'flash_failure'));", $contents);

the multiline modifier is key.

keisimone