2015-01-09 152 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);