首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP循环替换标记

PHP循环替换标记
EN

Stack Overflow用户
提问于 2015-01-09 21:29:22
回答 2查看 45关注 0票数 0

我正在尝试为网站上的链接、颜色和项目符号做自定义标记,这样l.../l就会被里面的链接所取代,li.../li就会被项目符号列表所取代。

我已经完成了一半的工作,但是链接描述有一个问题,代码如下:

代码语言:javascript
复制
// 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);
}

我遇到的问题是当我有三个链接时:

代码语言:javascript
复制
[l]http://www.example1.com[/l]
[l]http://www.example2.com[/l]
[l]http://www.example3.com[/l]

链接将被替换为:

代码语言:javascript
复制
http://www.example1.com
http://www.example1.com
http://www.example1.com

它们都是正确的超链接,即1,2,3,但文本位对于所有链接都是相同的。您可以在页面底部的操作here中看到它,其中包含三个随机链接。如何更改代码以使正确的URL描述显示在每个链接下-以便每个链接都正确地超链接到相应的页面,并带有显示该URL的相应文本?

EN

回答 2

Stack Overflow用户

发布于 2015-01-09 21:42:25

str_replace为你做了所有繁琐的工作。问题是:

代码语言:javascript
复制
getBetweenTags("[l]", "[/l]", $text)

不会改变。它将匹配3次,但它只是解析为"http://www.example1.com",因为这是页面上的第一个链接。

你不能真的做静态替换,你至少需要保留一个指针,指向你在输入文本中的位置。

我的建议是编写一个简单的标记器/解析器。实际上,这并不难。标记器可以非常简单,找到所有的[]并派生标签。然后,您的解析器将尝试理解这些标记。令牌流可能如下所示:

代码语言:javascript
复制
array(
    array("string", "foo "),
    array("tag", "l"),
    array("string", "http://example"),
    array("endtag", "l"),
    array("string", " bar")
);
票数 0
EN

Stack Overflow用户

发布于 2015-01-09 22:10:50

下面是我个人使用preg_match_all的方法。

代码语言:javascript
复制
$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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27861680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档