预处理g_match_all,然后替换为输入字符串


Preg_match_all and then replace for an input string

基本上我想解析一些有语法的输入内容,然后转换为html代码。

例如

$input="Please watch video 1 [{video('whats-new/chain_reaction-vid1.jpg')} width="580" 
height="326" alt="" video="Zb36h4K2IKQ"] and video 2 [{video('whats-new/chain_reaction-
vid2.jpg')} width="580" height="326" alt="" video="Zb36h4K2IDY"] . Enjoy.";

目前有一种方法可以使用为视频添加所有属性

$pattern="/video'(''K[^']*|(?:width|height|alt|video)='"'K[^'"]*/";
preg_match_all($pattern, $input, $matches);
print_r($matches);

虽然我可以得到$matches,但它似乎很难替换。

[{video('whats-new/chain_reaction-vid1.jpg')} width="580" height="326" alt="" video="Zb36h4K2IKQ"]

具有一些回调功能,可以将该部分转换为适当的html,如

<a href="youtube.com/Zb36h4K2IKQ"><img src="whats-new/chain_reaction-vid1.jpg" width="580" height="326" alt=""></a>

任何建议。

Regex:

'[{video'('([^']*)'')}([^']]*)'s+video="([^"]*)"]

替换字符串:

<a href="youtube.com/$3"><img src="$1"$2></a>

演示

<?php
$input='Please watch video 1 [{video(''whats-new/chain_reaction-vid1.jpg'')} width="580" 
height="326" alt="" video="Zb36h4K2IKQ"] and video 2 [{video(''whats-new/chain_reaction-
vid2.jpg'')} width="580" height="326" alt="" video="Zb36h4K2IDY"] . Enjoy.';
echo preg_replace("~'[{video'('([^']*)'')}([^']]*)'s+video='"([^'"]*)'"]~", '<a href="youtube.com/$3"><img src="$1"$2></a>', $input)
?>

输出:

Please watch video 1 <a href="youtube.com/Zb36h4K2IKQ"><img src="whats-new/chain_reaction-vid1.jpg" width="580" 
height="326" alt=""></a> and video 2 <a href="youtube.com/Zb36h4K2IDY"><img src="whats-new/chain_reaction-
vid2.jpg" width="580" height="326" alt=""></a> . Enjoy.