This is pretty easy with a callback:
$var = preg_replace_callback("`(?<=echo ')(.+)(?=';)`iU", function ($matches) { return addslashes($matches[1]); }, $var)
First, we map the string to echo quotes (and nothing more), then we use the addlashes function on what we found. The ungreedy (U) option is important, therefore. + Does not match the entire line.
source
share