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

时间:2017-12-11 01:53:15

标签: php regex

我正在与facebook即时文章合作开展一个项目。我想通过PHP脚本进行自动转换,但是我在重新格式化这段代码时遇到了问题

[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]

进入此代码

<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>

任何人都可以帮我解决这个问题吗? 我真的很感激任何帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

在一般情况下,你应该考虑使用某种形式的解析器来处理这个问题。话虽如此,如果您愿意仅使用单个正则表达式来接受风险,那么请考虑与查找模式匹配,并替换后面的模式:

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

以下是代码:

$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;

这将输出以下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

相关问题