V_RocKs
V_RocKs

Reputation: 134

PHP Loop using preg_replace or sprintf to swap MYSQL data with tags inside a string in ##tag## format

Say I have a returned array from a database with:

$row = array("percent" => "33%", "name" => "30 Cups", "price" => "$16");

I will also have a returned string of something like:

$string = "Take ##percent## off our newly released ##name## at just ##price## for the set!"

I am trying to find a way to loop through and change the $string to:

Take 33% off our newly released 30 Cups at just $16 for the set!

But, it should also work with a switched up $row and $string. As in $price and ##price## might change to $year and ##year## for a subscription item. I don't mind creating a key/value pair for assigning $year to ##year## or having it know that ##year## is $year via code.

The idea is that somebody else might come and create a string of:

$string = "XMAS is here and we have a ##percent## off deal on ##name##, hurry while supplies are still in stock!"

So the PHP code in the page will never be changed. It will just have something like:

<?= $tagline ?>

I don't need help on querying the DB or anything else other than how to switch out the ##tags## in $string with the data in $row. Any help would be appreciated.

Edit: At this point I would be happy just to be given some ideas on what a system of replacing formatted ##tags## like this would be called so I can try to find an example of it on github.

Upvotes: 2

Views: 348

Answers (1)

BornKillaz
BornKillaz

Reputation: 602

Use str_replace() and array_keys()

<?php

/**
 * replace_tags()
 * 
 * @param array $row
 * @param string $string
 * @return string
 */
function replace_tags( $row, $string ) {

    if( is_array( $row ) && !empty( $row) ) {

        $tags = array();
        $keys = array_keys( $row );

        foreach( $keys as $tag ) : $tags[] = '##' . $tag . '##'; endforeach;

        $string = str_replace( $tags, $row, $string );
    }

  return $string;   
}

$row = array( "percent" => "33%", "name" => "30 Cups", "price" => "$16" );

$string = "Take off ##percent## our newly released ##name## at just ##price## for the set!";  

$tagline = replace_tags( $row, $string );

echo $tagline;

?>

Upvotes: 1

Related Questions