2009-10-19 95 views
0

我有這種HTML,我正在從wordpress讀取到一個普通的PHP文件。這不是有效的HTML,但wordpress應該將[caption]去掉img標籤,並將其放入帶有標題的div中,作爲<p>標籤。但我想用PHP做這個,沒有wordpress。正則表達式將WordPress標籤轉換爲HTML

[caption id="" align="alignnone" width="190" caption="my caption"]html image tag would got here but got stripped[/caption] 

如何在正則表達式中執行此操作。不知何故,我正在想方設法使用preg_match_callback。

+0

WordPress的,你認爲是 「借用」 它的一些功能呢? – VolkerK 2009-10-19 08:31:48

+0

是的,那是我最初的計劃,但這是使用某種類型的短代碼API的,我不知道哪個類包括第一和什至不知道如何調用轉換短代碼 – jimiyash 2009-10-19 08:33:04

+0

感謝所有的答案的功能,我最終使用了VolkerK的答案並使用了wordpress includes。希望將來我可以使用partoa的部分答案。 – jimiyash 2009-10-19 14:36:07

回答

3

似乎爲了讓WordPress的代碼做所有你需要的是兩個文件plugin.php工作和shortcodes.php從WP-包括目錄。

require 'wordpress/wp-includes/plugin.php'; 
require 'wordpress/wp-includes/shortcodes.php'; 
add_shortcode('caption', 'handleCaption'); 
$content = '[caption id="foo" style="bar"]Marry had a little lamb[/caption]whose fleece was white as snow'; 
do_shortcode($content); 

function handleCaption($attributes, $content='') { 
    var_dump($attributes, $content); 
} 

打印

array(2) { 
    ["id"]=> 
    string(3) "foo" 
    ["style"]=> 
    string(3) "bar" 
} 
string(23) "Marry had a little lamb" 
1

這裏是一個可能的REG進出口。

$res = preg_match_all('/\[caption(.*?)\](.*?)\[\/caption\]/iU', 
'[caption id="" align="alignnone" width="190" caption="my caption"]html image tag would got here but got stripped[/caption]', 
$matches); 


var_dump($res, $matches); 

本身是用PHP編寫的輸出

int(1) 
array(3) { 
    [0]=> 
    array(1) { 
    [0]=> 
    string(122) "[caption id="" align="alignnone" width="190" caption="my caption"]html image tag would got here but got stripped[/caption]" 
    } 
    [1]=> 
    array(1) { 
    [0]=> 
    string(57) " id="" align="alignnone" width="190" caption="my caption"" 
    } 
    [2]=> 
    array(1) { 
    [0]=> 
    string(46) "html image tag would got here but got stripped" 
    } 
}