dongzheng4556 2017-12-11 01:53
浏览 46

PHP中的正则表达式用于提取和重新格式化

I am working on a project with facebook instant article. I would like to do automatic conversion through PHP script but I have problem with reformatting this code

[caption id="attachment_15737" align="aligncenter" width="1024"]<img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /> © ivote[/caption]

into this code

<figure><img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /><figcaption>© ivote</figcaption></figure>

Can anyone help me out with this problem? I would really appreciate any help. Thank you.

  • 写回答

1条回答 默认 最新

  • douyinbo3361 2017-12-11 02:17
    关注

    You should probably consider using some sort of formal parser to handle this problem in the general case. That being said, if you are willing to accept the risks with just using a single regex, then consider matching with the finding pattern, and replacing with the pattern after it:

    /\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/
    <figure>$1<figcaption>$2</figcaption></figure>
    

    Here is the code:

    $input = "[caption id=\"attachment_15737\" align=\"aligncenter\" width=\"1024\"]<img class=\"wp-image-15737 size-full\" title=\"bathroom counter decor\" src=\"https://roohome.com/wp-content/uploads/2017/11/ivote.jpg\" alt=\"bathroom counter decor\" width=\"1024\" height=\"768\" /> © ivote[/caption]";
    $after = preg_replace('/\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/', '<figure>$1<figcaption>$2</figcaption></figure>', $input);
    echo $after;
    

    This outputs the following HTML:

    <figure><img class="wp-image-15737 size-full" title="bathroom counter decor"
                 src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg"
                 alt="bathroom counter decor" width="1024" height="768" />
            <figcaption>© ivote</figcaption>
    </figure>
    

    Demo

    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教