2015-01-09 149 views
0

我試圖做一個網站上的鏈接,顏色和項目符號點的自定義標籤,所以[l] ... [/ l]被內部鏈接和[李]取代... [/ li]被一個項目符號列表所取代。PHP循環代替標籤

我有一半的工作,但有一個問題與鏈接的描述,繼承人的代碼:

// Takes in a paragraph, replaces all square-bracket tags with HTML tags. Calls the getBetweenTags() method to get the text between the square tags 
function replaceTags($text) 
{ 
    $tags = array("[l]", "[/l]", "[list]", "[/list]", "[li]", "[/li]"); 
    $html = array("<a style='text-decoration:underline;' class='common_link' href='", "'>" . getBetweenTags("[l]", "[/l]", $text) . "</a>", "<ul>", "</ul>", "<li>", "</li>"); 

    return str_replace($tags, $html, $text); 
} 

// Tages in the start and end tag along with the paragraph, returns the text between the two tags. 
function getBetweenTags($tag1, $tag2, $text) 
{ 
    $startsAt = strpos($text, $tag1) + strlen($tag1); 
    $endsAt = strpos($text, $tag2, $startsAt); 

    return substr($text, $startsAt, $endsAt - $startsAt); 
} 

我遇到的問題是,當我有三個環節:

[l]http://www.example1.com[/l] 
[l]http://www.example2.com[/l] 
[l]http://www.example3.com[/l] 

鏈接被替換爲:

http://www.example1.com 
http://www.example1.com 
http://www.example1.com 

它們都是正確的超鏈接,即1,2,3但文本bi t對所有鏈接都是一樣的。 你可以在頁面底部用三個隨機鏈接在行動here中看到它。我如何更改代碼以在每個鏈接下顯示正確的URL描述 - 因此,每個鏈接都正確超鏈接到相應的頁面,並顯示相應的URL以顯示該URL?

+1

您確定每次請求函數時都會更改參數嗎? – Neat

+0

我認爲最近發生的事情是它給了包含3個鏈接的整個段落,正確地替換每個標記,但只調用getBetweenTags()標記一次,然後將這個描述放在三個鏈接的每一個上 - 我如何調整代碼以告訴每當它遇到一組新的方形標籤時,它會getBetweenTags()? – Crizly

回答

0

str_replace爲你做了所有的咕嚕工作。問題是:

getBetweenTags("[l]", "[/l]", $text) 

不變。它會匹配3次,但它只是解析爲"http://www.example1.com",因爲這是頁面上的第一個鏈接。

你不能真正做一個靜態替換,你至少需要一個指向你在輸入文本中的位置的指針。

我的建議是編寫一個簡單的標記器/解析器。其實並不難。分詞器可以非常簡單,找到所有[]並派生標籤。然後你的解析器會嘗試理解令牌。您的令牌流可能類似於:

array(
    array("string", "foo "), 
    array("tag", "l"), 
    array("string", "http://example"), 
    array("endtag", "l"), 
    array("string", " bar") 
); 
0

以下是我將如何使用preg_match_all而不是個人身份。

$str=' 
[l]http://www.example1.com[/l] 
[l]http://www.example2.com[/l] 
[l]http://www.example3.com[/l] 
'; 
preg_match_all('/\[(l|li|list)\](.+?)(\[\/\1\])/is',$str,$m); 
if(isset($m[0][0])){ 
    for($x=0;$x<count($m[0]);$x++){ 
     $str=str_replace($m[0][$x],$m[2][$x],$str); 
    } 
} 
print_r($str);