Replace template based on placeholder values

Posted on

Problem

I have wrote a PHP template code to replace placeholders based on the value provided within the placeholder. For example the content may have placeholders like
{ITEM-100} {ITEM-110} and I want to replace them with a text made by the details fetched from db with item_id=100 or item_id=110.

The code below id working fine, and I would like to get suggestions to improve the performance of the code. Thanks in advance.

$content = 'Here is the item list {ITEM-100}  {ITEM-110}  {ITEM-200}';    

if(preg_match_all('/{ITEM-.*?}/', $content, $matches))
{
    foreach($matches[0] as $v) 
    {
        $value = trim($v, '{}');
        $val_chunk = explode('-', $value);
        if(isset($val_chunk[1])){
            $item_card = get_item_card($val_chunk[1]);
            $content = str_replace($v, $item_card, $content);    
        }           
    }  
}

echo $content;

Solution

The best way to improve the performance of this code is probably by using the preg_replace_callback()-function. This function allows you to search for a regex in a string, and call a function for every match. This function then returns the replacement. This avoids running multiple str_replace() operations over the string, which can be costly for large strings.

Secondly, we can use a capture group in the regex to avoid the use of explode(). I.e. by changing the regex from /{ITEM-.*?}/ to /{ITEM-(.*?)}/ we can ensure that we get the matched item identifier directly.

Applying those two modifications, we would end up with something like:

$content = 'Here is the item list {ITEM-100}  {ITEM-110}  {ITEM-200}';    
function get_replacement($matches) {
    $value = $matches[1]; // Index 1 is the first capture group, which contains our item number.
    return get_item_card($value);
}
$content = preg_replace_callback('/{ITEM-(.*?)}/', 'get_replacement', $content);
echo $content;

Leave a Reply

Your email address will not be published. Required fields are marked *