【问题标题】:PHP BBCode related issue. How to get values between two tags?PHP BBCode 相关问题。如何获取两个标签之间的值?
【发布时间】:2012-02-03 00:03:42
【问题描述】:

我需要为我的网站执行以下操作。

$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] 标记之间的值。它应该得到它找到的所有正确匹配,而不是第一个匹配。

【问题讨论】:

    标签: php function replace bbcode


    【解决方案1】:

    如果您在 $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 发送它。

    【讨论】:

    • 谢谢。顺便说一句,我应该如何替换这些值?通过使用 str_replace 或 preg_replace_callback 代替?哪一种方式会更有效并提供更好的性能?
    • 我首选的替换方式是 preg_replace_callback。它使处理文本变得更加容易,因为 str_replace 必须为每个实例单独调用,而 preg_replace_callback 只需调用一次。如果您在处理之前已经有要替换的文本,也可以使用 preg_replace_callback 代替 preg_match_all。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多