-->

PHP BBCode related issue. How to get values betwee

2019-07-24 23:18发布

问题:

I need to do the following for my website.

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

The BBCode function is like this:

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>';
}

Okay, I already asked my questions between functions. I hope you understood what I am trying to do.

Basically, anything between [item] and [/item] tags will be converted into an image, but the image path of each items will be taken from database.

The part I am having hard times is getting values between [item] and [/item] tags correctly. It should be getting all the correct matches it finds, not the first match.

回答1:

If you use a preg_match_all on $string, you'll get a result set with all the matches:

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

$results will have an array of results that looks like this:

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

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

)

Now you should be able to loop through the $results[1] and send it through convertItems.