dongyan9838 2013-08-26 07:59
浏览 146
已采纳

在php中解析模板字符串

I am having an issue with string parsing in php. I am trying to create my own template parser (for my learning purpose). I have decided to put urls in the following format {url:abc/def} so this would be displayed like http://www.domain.com/abc/def. I have tried using str_replace but in this case it would not work since the value after ":" could be anything. Exploding the string also wont work as ":" can also be present in the text of html file. I think this could be only done via regular expression so suggest me some good regular expression also do let me know if this can be achieved via any other approach.

Other things to note.

  1. Since it is used for template parsing and template can have multiple urls.
  2. Urls would not have any query strings but i would appreciate if the solution also supports them.
  • 写回答

1条回答 默认 最新

  • doubo1883 2013-08-26 08:11
    关注

    for learning purposes then:

    preg_replace('/\{url:([^\}]*)\}/', $base_url.'$1', $string);
    

    And the explanation of the regex

    1. \{url: <-- find this text
    2. [^\}]* <-- this means 'any character but a } occuring 0 or more times
    3. ([^\}]*) <-- by putting it inbetween () we can later reference it (see the '$1')
    4. \} <-- the closing }

    As long as you're learning: take a look at http://www.regular-expressions.info/ for more info on regular expressions. They're quite awesome really :D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件