I’m trying to parse a php code using some regex and I’m stuck at how to use preg_replace() to replace the last } with the string I want. Here’s a sample code:
$data = '<?php
class Myclass {
function index() {
}
} // <- I want to replace that curly brace
?>';
$data = preg_replace('##is','// my new string here',$data);
Any idea how ?
Find last curly brace and replace all characters after it with a string
Using the search pattern:
"(\})[^\}]*$"should do it:Find last curly brace and replace only the brace itself with a string
Use a negative lookahead such as this:
\}(?!.*\})More info: http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/