PHP的BBCode相关的问题。如何获得两个标签之间的值?
问题描述:
我需要做我的网站下面。PHP的BBCode相关的问题。如何获得两个标签之间的值?
$comment = "[item]Infinity Edge[/item]<br>[item]Eggnog Health Potion[/item]";
$this->site->bbcode->postBBCode($comment);
BB代码的功能是这样的:
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>';
}
好吧,我已经要求我的功能之间的问题。我希望你明白我想要做的事情。
基本上,[项目]和[/项目]标签之间的任何东西将被转换成图像,但每个项目的图像路径将从数据库中取得。
[项目]和[/项目]之间我有困难的时候的部分是让值正确标记。它应该获得它找到的所有正确匹配,而不是第一个匹配。
答
如果您使用$字符串preg_match_all,你会得到一个结果集的所有比赛:
$results = array();
preg_match_all('#\[item\](.*?)\[\/item\]#', $string, $results);
$结果就会有结果的数组,看起来像这样:
Array
(
[0] => Array
(
[0] => [item]Infinity Edge[/item]
[1] => [item]Eggnog Health Potion[/item]
)
[1] => Array
(
[0] => Infinity Edge
[1] => Eggnog Health Potion
)
)
现在你应该可以遍历$结果[1],并通过convertItems发送。
谢谢。顺便说一句,我应该如何替换值?通过使用str_replace或preg_replace_callback来代替?哪一个会更有效率,更好的表现? – Aristona 2012-01-05 06:49:51
我进行替换的首选方法是preg_replace_callback。它使得处理文本变得容易很多,因为str_replace必须为每个实例单独调用,而preg_replace_callback只需要调用一次。 如果您在处理之前已经替换了文本,preg_replace_callback也可以用来代替preg_match_all。 – 2012-01-05 15:46:07