Search code examples
phpregexreplaceforeachpreg-match-all

Replace curly braced placeholders containing a word followed by an integer


I've got a huge text which contains strings following the pattern:

{text1} {text2} ... {text10}

"text" will remain the same but the number which comes after will always be incremented. I can't predict its maximum.

Until today I've used this:

preg_match_all("{text.}", $content, $occurrences);
foreach ($occurrences[0] as $occurrence){
    $content = str_replace("{" . $occurrence . "}", "test", $content);
}

Everything worked fine until today when I've noticed that the preg_match_all() rule doesn't work if I've got to replace multiple digits. This means basically it will detect "text2" but it won't detect "text10".

How should I alter this preg_match() rule to detect any number after "text"?


Solution

  • preg_match_all("{text\d+}", $content, $occurrences);
    

    or

    preg_match_all("{text.+}", $content, $occurrences);
    

    Try this. . matches only one character. That is why text2 is matched but not text10 as there are 2 characters after text.