PHP BBCode相关问题.如何获取两个标记之间的值


PHP BBCode related issue. How to get values between two tags?

我需要为我的网站做以下事情。

$comment = "[item]Infinity Edge[/item]<br>[item]Eggnog Health Potion[/item]";
$this->site->bbcode->postBBCode($comment);

BBCode功能如下:

function postBBCode($string)
{
            $string = nl2br($string);
            $string = strip_tags($string, '<br></br>');
            $string = $this->tagItem($string);
            return $string;
}
function tagItem($string)
{
     //Get all values between [item] and [/item] values
     //Appoint them to an array.
     //foreach item_name in array, call convertItems($item_name) function.
     //Now, each item_name in array will be replaced with whatever  convertItems($item_name) function returns.
     //return modified string
}
function convertItems($itemName)
{
    // -- I already made this function, but let me explain what it does.
    //Query the database with $itemName.
    //Get item_image from database.
    //Return '<img src="$row['item_image']></img>';
}

好吧,我已经在函数之间问过我的问题了。我希望你能理解我的意图

基本上,[item]和[/item]标签之间的任何内容都将被转换为图像,但每个项目的图像路径都将取自数据库。

我遇到困难的部分是正确地获取[item]和[/item]标记之间的值。它应该得到它找到的所有正确匹配项,而不是第一个匹配项。

如果在$string上使用preg_match_all,则会得到一个包含所有匹配项的结果集:

    $results = array();
preg_match_all('#'[item'](.*?)'['/item']#', $string, $results);

$results将有一个结果数组,如下所示:

Array
(
    [0] => Array
        (
            [0] => [item]Infinity Edge[/item]
            [1] => [item]Eggnog Health Potion[/item]
        )
    [1] => Array
        (
            [0] => Infinity Edge
            [1] => Eggnog Health Potion
        )
)

现在,您应该能够循环遍历$results[1]并通过convertItems发送它。