Preg_replace by replacing only part of the template in ()?

Sorry for this basic question, but I am looking through all the information about preg_replace that I can find, and I still cannot figure it out. I have a big line, for example:

  $string= '# tjs { fassdaf } #fsk { fssf} # fskff { casf }';

And when I do this, it replaces the entire template, not just the part in (), as I expect this to happen. I am wondering how can I just replace the part in () .. thanks

  $pattern= '/#.*tjs.*\{.*(.*)\}/imsU';
  $replacement= "test";
  $return_string = preg_replace ($string, $pattern, $replacement );

expected replacement string:

'# tjs {test} #fsk { fssf} # fskff { casf }';
+5
source share
1 answer
$pattern= '/(#\s*tjs\s*\{\s*)(.*?)(\s*\})/imsU';
$replacement= "test";
$return_string = preg_replace($pattern,'$1'.$replacement.'$3',$string);
+3
source

All Articles