inbound-mktg
inbound-mktg

Reputation: 11

Replace price shortcode with actual price from array

I have a price shortcode like these:

[price ELEPHANT]
[price MONKEY_345]
[price TIGER.3TAIL]

where the word in caps (with the extension, if any) is the product SKU.

I've run a database query for SKU and PRICE, so now I want to replace the shortcode in my text to the actual price of the item.

[price ELEPHANT] becomes 46.97

1.) I have been working with preg_replace, but can't get it to work with "." or "_" in the SKU:

$text = '<p>We have the price: [price CANOPY3.75B]. This is some more text.</p>';
$pattern = '/\[(\w+) (\w+)\]/';
$replacement = '$2';
echo preg_replace($pattern, $replacement, $text);

2.) Once I identify the shortcode SKU value, how do I use it to search the array for the associated price?

(Hope I did the code blocks OK -- this is my first post here.)

Upvotes: 0

Views: 111

Answers (1)

Placido
Placido

Reputation: 1385

Let's say you have the following array with the "name-price" pairs:

$prices = array('ELEPHANT' => 46.97, 'CANOPY3.75B' => 20.35, 'TIGER.3TAIL' => 30 ... etc.);

Then you can use the following piece of code:

$prices = array('ELEPHANT' => 46.97, 'CANOPY3.75B' => 20.35, 'TIGER.3TAIL' => 30,);

$text = '<p>We have the price: [price CANOPY3.75B]. This is some more text.</p>';
$pattern = '/\[price (.*?)\]/';
echo preg_replace_callback($pattern, 
        function($match)
        { 
            global $prices;
            return isset($prices[$match[1]]) ? $prices[$match[1]] : $match[1]; 
        }, 
        $text);
//output: We have the price: 20.35. This is some more text.

Upvotes: 1

Related Questions