2011-08-14 133 views
-2

我有例如FAQ腳本幫助

$str = "[H]Test[/H] My test string [H]Test2[/H] My second Test string"; 

一個字符串,我想使內部名單「[H]」,並讓他們點擊能夠像

<a href="#faq-1">Test</a> 
<a href="#faq-2">Test2</a> 

,並也想包括這

<a name="faq-1"></a>Test 
<a name="faq-2"></a>Test2 
$str

任何幫助,請

+0

使用正則表達式的好地方 – Ibu

+0

在請求這裏之前請考慮做一些搜索。 –

+0

我真的不明白。你想在鏈接到同一個地方的[H]標籤內製作一個列表嗎?你不是說你想要一個單獨的鏈接到文本元素的列表。 – kjetilh

回答

1

這是我想出來的。

<?php 

$str = "[H]Test[/H] My test string [H]Test2[/H] My second Test string"; 

/** 
* Helper class 
*/ 
class FaqHelper { 
    static $count = 1; 
    static $listItems = array(); 
    static $prefix = 'faq-'; 

    static function GetList() { 

     $items = ''; 
      foreach (self::$listItems as $id => $label) { 
       $items .= '<li><a href="#' . self::$prefix . $id .'">' . $label . '</a></li>'; 
      } 

     return '<ul>'. $items .'</ul>'; 
    } 

    static function ReplaceCallback($matches) 
    { 
     $id = self::$count; 
     $label = $matches[1]; 

     self::$listItems[$id] = $label; 

     $res = '<span id="'. self::$prefix . $id .'">' . $label . '</span>'; 

     self::$count++; 

     return $res; 
    } 
} 

$text = preg_replace_callback(
    "#\[H\]([^\[]+)\[/H\]#", 
    array('FaqHelper', "ReplaceCallback"), 
    $str 
); 

$list = FaqHelper::GetList(); 

echo $list; 
echo '<br /><br />'; 
echo $text; 

?> 
+0

非常感謝你 – Hafiz

+0

np。請注意,我更新了片段,並將FaqHelper類中的preg_replace_callback移動到內部,進一步封裝了類中的功能。如果回答您的問題,請將答案標記爲答案。 – kjetilh

+0

kjetilh請檢閱這一個也謝謝 http://stackoverflow.com/questions/7061578/ph​​p-list-of-contents – Hafiz