0

我有一个这样的价格简码:

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

其中大写字母(带有扩展名,如果有的话)是产品 SKU。

我已经对 SKU 和 PRICE 运行了数据库查询,所以现在我想将文本中的简码替换为商品的实际价格。

[price ELEPHANT]变成46.97

1.) 我一直在使用 preg_replace,但无法使用“。” 或 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.) 一旦我确定了简码 SKU 值,我如何使用它在数组中搜索相关价格?

(希望我的代码块没问题——这是我在这里的第一篇文章。)

4

1 回答 1

1

假设您有以下带有“名称-价格”对的数组:

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

然后您可以使用以下代码:

$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.
于 2013-02-02T16:14:30.220 回答