2012-12-06 67 views
0

我目前正在玩一些正則表達式,並希望在我的網站上爲文本實現某種自定義標籤。例如,如果我想實現圖片插入一個文本,我用下面的支架標籤這麼做......preg_match_all:匹配自定義標籤

Lorem存有悲坐阿梅德(圖片:tiger.jpg寬度:120高度:200 標題:此圖爲虎) SED直徑nonumy eirmod tempor invidunt

現在我想我的PHP腳本爲1。找到這些支架標籤和2.本括號讀取單一的標籤,所以我得到某種類似的陣列...

$attributes = array(
    'image' => 'tiger.jpg', 
    'width' => '150', 
    'height' => '250', 
    'title' => 'This picture shows a tiger', 
); 

對我來說(對我而言)棘手的部分是,「值」可以包含所有內容,只要它不包含像(\w+)\:這樣的內容 - 因爲這是不同標記的開始。下面的代碼片段代表了我目前爲止的內容 - 找到方括號 - 目前爲止的作品,但將括號內容拆分爲單個標籤實際上並不奏效。我用(\w+)作爲佔位符匹配值 - 這不匹配「tiger.jpg」或「這張圖片顯示一隻老虎」或其他東西。我希望你明白我的意思! ;)

<?php 

$text = 'Lorem ipsum dolor sit amet (image: tiger.jpg width: 150 height: 250 title: This picture shows a tiger) sed diam nonumy eirmod tempor invidunt'; 

// find all tag-groups in brackets 
preg_match_all('/\((.*)\)/s', $text, $matches); 

// found tags? 
if(!empty($matches[0])) { 

    // loop through the tags 
    foreach($matches[0] as $key => $val) { 

     $search = $matches[0][$key]; // this will be replaced later 
     $cache = $matches[1][$key]; // this is the tag without brackets 

     preg_match_all('/(\w+)\: (\w+)/s', $cache, $list); // find tags in the tag-group (i.e. image, width, …) 

     echo '<pre>'.print_r($list, true).'</pre>'; 

    } 

} 

?> 

如果有人能幫我解決這個問題,會很棒!謝謝! :)

+1

難道你不能使用模板庫,而不是從頭開始做這件事嗎? – Barmar

+0

當然,我可以,但我更願意自己做,因爲模板庫會是一個完全不必要的功能,它並不是那麼簡單的事情! ;) –

+0

周圍有一些相當輕量級的模板庫。並且要記住,這類事情最大的問題之一就是安全性。滾動你自己的模板系統很可能導致XSS漏洞。 – SDC

回答

0
<? 

$text = 'Lorem ipsum dolor sit amet (image: tiger.jpg width: 150 height: 250 title: This picture shows a tiger) sed diam nonumy eirmod tempor invidunt'; 

// find all tag-groups in brackets 
preg_match_all('/\(([^\)]+)\)/s', $text, $matches); 
$attributes = array(); 

// found tags? 
if ($matches[0]) { 
    $m = preg_split('/\s*(\w+)\:\s+/', $matches[1][0], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
    for ($i = 0; $i < count($m); $i+=2) $attributes[$m[$i]] = $m[$i + 1]; 
} 

var_export($attributes); 

/* 
array (
    'image' => 'tiger.jpg', 
    'width' => '150', 
    'height' => '250', 
    'title' => 'This picture shows a tiger', 
) 
*/