dousui3124 2013-11-05 05:19
浏览 32

RegEx处理和更改字符串中的多个链接

I am having a hard time figuring this out:

I have a string ($data) which contains some links formatted this way:

[pagelink]Folder/File[/pagelink]

The $data contains multiple of these links.

I need to replace these links with actual html links and I have this code to do it (which works):

$data = preg_replace('/\[pagelink\](.*?)\[\/pagelink\]/is','<a href="$1">$1</a>',$data);

Now I would like to remove all the "Folder" instances from the part of the link that is showed to the user without actually altering the link itself; in other words if the link is this:

[pagelink]Folder/File[/pagelink]

I would like it to become this:

<a href="Folder/File">File</a>

What I tried is this:

$data = preg_replace('/\[pagelink\](.*?)\[\/pagelink\]/is','<a href="$1">'.( strstr($1) === false ? $1 : str_replace('/','',strstr($1)) ).'</a>',$data);

but I get a bunch of errors so I guess I can't use back references this way.

Could you guys help me out please? Thanks

  • 写回答

4条回答 默认 最新

  • duan1227 2013-11-05 05:31
    关注

    Revise your regular expression so the folder and file are in separate capture groups.

    $data = preg_replace('#\[pagelink\](.*?/)?([^/]*?)\[/pagelink\]#is','<a href="$1$2">$2</a>',$data);
    

    Capture group 1 gets Folder/, capture group 2 gets File.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决