Search code examples
phpregexdynamicpreg-replaceplaceholder

Replace square brace placeholder with dynamic replacement text


I have a placeholder in text like this one: [demo category=1] and I want to replace the placeholder with the content of category number 1 e.g. This is the Content of my first Category

This is my starting point pattern - that's all I have: '/[demo\s*.*?]/i';


Solution

  • Firstly, you need to escape the square brackets as they are special characters in PCREs:

    '/\[demo\s*.*?\]/i';
    

    Secondly, it sounds like you want to do something with the digit at the end, so you'll want to capture it using parenthesis:

    '/\[demo\s*.*?=(\d+)\]/i';
    

    The braces will capture \d+ and store it in a reference. \d+ will match a string of numbers only.

    Finally, it sounds like you need to use preg_replace_callback to perform a special function on the matches in order to get the string you want:

    function replaceMyStr($matches)
    {
        $strNum = array("1"=>"first", "2"=>"second", "3"=>"third"); // ...etc
        return "This is the Content of my ".$strNum($matches[1])." Category.";
        // $matches[1] will contain the captured number
    }
    preg_replace_callback('/\[demo\s*.*?=(\d+)\]/i', "replaceMyStr", "[demo category=1]");