1

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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 codepad.viper-7.com/V3BS6H
What exactly do you mean by does not work? Try printing the value of $contents after you get it using file_get_contents
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. codepad.viper-7.com/1twh2k
0

the solution is thus:

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

the multiline modifier is key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.