2012-01-05 2 views
1

私のウェブサイトは次のようにする必要があります。PHP BBCode関連の問題。 2つのタグ間で値を取得する方法は?

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

さて、私はすでに、機能間の私の質問をしました。私は何をしようとしているのか理解してくれることを願っています

基本的に[item]タグと[/ item]タグの間のものはイメージに変換されますが、各アイテムのイメージパスはデータベースから取得されます。

私は苦労している部分が[item]タグと[/ item]タグの間の値を正しく取得しています。最初の試合ではなく、見つかったすべての正しい試合が得られるはずです。あなたは$文字列にpreg_match_allを使用する場合は

答えて

2

、あなたはすべての試合で結果セットを取得します:

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

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

) 

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

$結果は次のようになり、結果の配列を持つことになります

これで、$ results [1]をループしてconvertItemsを通して送信できるはずです。

+0

ありがとうございます。ところで、私は値を置き換えるべきですか?代わりにstr_replaceまたはpreg_replace_callbackを使用しますか?どの方が効率的なやり方でより良いパフォーマンスを得ることができますか? – Aristona

+0

私の交換を行うための私の好ましい方法は、preg_replace_callbackです。 str_replaceは各インスタンスに対して個別に呼び出さなければならず、preg_replace_callbackを一度呼び出すだけで済むので、テキストの処理がより簡単になります。 処理前にテキストを置換する必要がある場合は、preg_match_allの代わりにpreg_replace_callbackを使用することもできます。 –

関連する問題