PHP将String替换为函数的Result

时间:2013-01-17 12:34:12

标签: php replace

我有一个包含HTML的PHP​​变量。我需要检查字符串的occourances,并将该字符串替换为函数的结果。

该函数尚未编写,但只需要传递一个变量,该变量将是产品的ID。

例如,该网站有产品,我希望用户能够在wysiwyg编辑器中键入内容,如{{product=68}},它将显示一个预设的div容器,其中包含该产品的信息。在这种情况下,产品在数据库中具有ID 68,但它可以是从1到任何东西。

我考虑创建一个产品ID数组并搜索字符串的第一部分,但觉得它可能相当麻烦,我认为我们的常驻reg exp天才可能能够揭示我需要的东西要做。

所以问题是......我如何在字符串中搜索{{product=XXX}}的遮挡物,其中XXX可以是大于1的整数,捕获该数字,并将其传递给创建替换字符串的函数ultimatley替换字符串的occourance?

2 个答案:

答案 0 :(得分:1)

这是一个与{{product = ##}}匹配的正则表达式(与您输入的数字无关):

{{product=([0-9]+)}}

编辑:对不起,没看到你想要从1开始:

{{product=([1-9][0-9]*)}}

如果你想捕获数字,就像这样:

$string = '{{product=68}}';
preg_match_all( '%{{product=([1-9][0-9]*)}}%', $string, $matches );
$number = (int) $matches[1][0];

为了让您更好地了解preg_match_all,这是$matches的内容:

array
  [0] => array // An array with strings that matched the whole regexp
    [0] => '{{product=68}}'
  [1] => array // An array with strings that were in the first "match group", indicated by paranthesis in the regexp
    [0] => '68'

E.g。如果您使用字符串“{{product = 68}} {{product = 70}}”,则$matches会如下所示:

array
  [0] => array
    [0] => '{{product=68}}'
    [1] => '{{product=70}}'
  [1] => array
    [0] => '68'
    [1] => '70'

答案 1 :(得分:1)

为你做一个小班,应该做你需要的。

<?php
class textParser{
    const _pattern = '/{{([a-z\-_]+)=([0-9]+)}}/';
    static protected $_data = false;

    static public function setData($data){
        self::$_data = $data;
    }
    static function parseStr($str){
        // Does a preg_replace according to the 'replace' callback, on all the matches
        return preg_replace_callback(self::_pattern, 'self::replace', $str);
    }
    protected static function replace($matches){
        // For instance, if string was {{product=1}}, we check if self::$_data['product'][1] is set
        // If it is, we return that
        if(isset(self::$_data[$matches[1]][$matches[2]])){
            return self::$_data[$matches[1]][$matches[2]];
        }
        // Otherwise, we just return the matched string
        return $matches[0];
    }
}
?>

单元测试/基本用法

<?php
// User generated text-string
$text = "Item {{product=1}} and another {{category=4}} and a category that doesnt exist: {{category=15}}";
// This should probably come from a database or something
$data = array(
    "product"=>array(
        1=>"<div>Table</div>"
      , 2=>"<div>Tablecloth</div>"
    )
  , "category"=>array(
        4=>"Category stuff"
    )
);
// Setting the data
textParser::setData($data);
// Parsing and echoing
$formated = textParser::parseStr($text);
echo $formated;
// Item <div>Table</div> and another Category stuff and a category that doesnt exist: {{category=15}}
?>