Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find text inside curly braces and replace text including curly braces

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

like image 440
Shadow Avatar asked Oct 17 '22 12:10

Shadow


1 Answers

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 }} text

Then, 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.

like image 84
Wiktor Stribiżew Avatar answered Oct 21 '22 02:10

Wiktor Stribiżew