duanfu3884 2013-09-23 18:48
浏览 19
已采纳

PHP正则表达式 - 对于[[_string_]],返回_string_?

Developing a shorthand parser as part of a client's application. I want to set up a shorthand for creating links similar to mediawiki.

I.E.: [[link_location|link_title]] eventually becomes <a href="link_location">link_title</a>

What I need to do is extract the string from between the brackets so I can process it; there's a bunch of validation and keyword conversion to do before it can go into a link. I'm pretty new to preg_match - I can match the bracketed expression with /\[\[(.*?)\]\]/, but I have no idea how to extract the string from the middle. Can anyone tell me what I'm missing? Or, if I'm going about this all wrong, have mercy and point me in the right direction?

Thanks!

EDIT: I should have clarified: I need to extract the string and process it, so preg_replaceing it directly into a link won't work in this case.

  • 写回答

2条回答 默认 最新

  • drflkphi675447 2013-09-23 18:51
    关注
    $string = preg_replace("/\[\[([^\|]+)|([^\]]+)\]\]/", "<a href=\"\\1\">\\2</a>", $string);
    

    more

    http://php.net/manual/en/function.preg-replace.php

    p.s. not tested.


    as for edit:

    preg_match("/\[\[([^\|]+)\|([^\]]+)\]\]/", $input, $m);
    
    $m[1] -- now is the location
    $m[2] -- now is the title
    

    and if you have many:

    preg_match_all("/\[\[([^\|]+)\|([^\]]+)\]\]/", $input, $m);
    
    $m[1] -- now contains all location occurrences
    $m[2] -- now contains all title occurrences 
    

    [edit] fixed bugs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败