I would like to find a pattern {text} and replace text including curly braces.
$data = 'you will have a {text and text} in such a format to do {code and code}';
$data= preg_replace_callback('/(?<={{)[^}]*(?=}})/', array($this, 'special_functions'),$data);
and my special function contain the callback code to replace the braces and completely and text conditionally.
public function special_functions($occurances){
$replace_html = '';
if($occurances){
switch ($occurances[0]) {
case 'text and text':
$replace_html = 'NOTEPAD';
break;
case 'code and code':
$replace_html = 'PHP';
break;
default:
$replace_html ='';
break;
}
}
return $replace_html;
}
Expected Output
you will have a NOTEPAD in such a format to do PHP
How can i replace text and curly braces at the same time using preg_replace_callback in php using regex
You need to edit the pattern like this:
$data = preg_replace_callback('/{{([^{}]*)}}/', array($this, 'special_functions'), $data);
The {{([^{}]*)}} pattern will match:
{{ - {{ substring([^{}]*) - Group 1: any 0+ chars other than { and }
}} - a }} textThen, inside the special_functions function, replace switch ($occurances[0]) with switch ($occurances[1]). The $occurrances[1] is the text part captured with the ([^{}]*) pattern. Since the whole match is {{...}} and the captured is ..., the ... is used to check the possible cases in the switch block, and the braces will get removed since they were consumed (=added to the match value that is replaced as a result of the preg_replace_callback function).
See the PHP demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With