dongyo7931 2015-11-21 04:50
浏览 30
已采纳

php将字符串替换为html标记

I want to display content in a php page from a .txt and change some tag to a html code like the following using:

Change this:

[img: something.jpg]

To this:

<img src="something.jpg" />  

I've tried to use preg_replace, but I have no idea how to use those symbols like /(){}^*.:. What it means to use things like this to extract some variables $1 $2 from a string?

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
  • 写回答

2条回答 默认 最新

  • donglengli0644 2015-11-21 05:00
    关注

    You can use the following regex like as

    \[(\w+):\s?(\w+.\w+)]
    

    Regex Explanation

    • \[ : \[ will check for [ literally.
    • (\w+): : (\w+) Capturing groups of any word character [a-zA-Z0-9_]. + Between one and unlimited times, as many times as possible, : will check for : literally
    • \s? : match any white space character [ \t\f ]. ? Between zero and one time, as many times as possible
    • (\w+.\w+) : Capturing group of any word character [a-zA-Z0-9_]

    So using preg_replace like as

    echo preg_replace('/\[(\w+):\s?(\w+.\w+)]/',"<$1 src='$2' />","[img: something.jpg]");
    

    Regex

    Demo

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?