我正在尝试为网站上的链接、颜色和项目符号做自定义标记,这样l.../l就会被里面的链接所取代,li.../li就会被项目符号列表所取代。
我已经完成了一半的工作,但是链接描述有一个问题,代码如下:
// 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,但文本位对于所有链接都是相同的。您可以在页面底部的操作here中看到它,其中包含三个随机链接。如何更改代码以使正确的URL描述显示在每个链接下-以便每个链接都正确地超链接到相应的页面,并带有显示该URL的相应文本?
发布于 2015-01-09 21:42:25
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")
);发布于 2015-01-09 22:10:50
下面是我个人使用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);https://stackoverflow.com/questions/27861680
复制相似问题