2014-09-30 29 views
0

基本上我想解析一些輸入內容,它有一些語法,然後轉換爲html代碼。Preg_match_all然後替換爲輸入字符串

例如

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

任何建議。

回答

0

正則表達式:

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

替換字符串:

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

DEMO

<?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. 
+0

謝謝,我應該使用preg_match_all或preg_replace?在輸入中還有多個視頻 – onegun 2014-09-30 04:11:00

+0

** preg_replace ** – 2014-09-30 04:13:22

+0

$ pattern =「/ \ [{video \('([^'] *)'\)}([^ \]] *)\ s + video如果(preg_match($ pattern,$ center,$ matches)){ $ center = preg_replace($ pattern,'',$ center)= \「([^ \」] *)\「]/gm」; if ; }說錯誤消息:preg_match():未知的修飾符'g' – onegun 2014-09-30 04:17:46

相關問題