2015-10-04 22 views
0

我正在創建一個系統,其中會有{這些標籤,其中包含文檔的各個級別的文件} 。在{這兩個}字符之間抓取任何東西的實例PHP

如何有效獲取內容?

實施例:

// this is a php/html doc. 
    {variablename} <<< how can i grab all instances like this, then do something? 

本質上採取的文件,並且與右輸出替換標籤的所有實例和然後返回該文件。這是我的任務。

+0

使用正則表達式?或者只是'str_replace',如果你只想替換它們。 –

回答

1

使用正則表達式:

$s = 'this is some {text} and {more}'; 
$p = "/{(.*)}/U"; 
preg_match_all($p,$s,$m); 
var_dump($m); 

輸出:

array(2) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(6) "{text}" 
    [1]=> 
    string(6) "{more}" 
    } 
    [1]=> 
    array(2) { 
    [0]=> 
    string(4) "text" 
    [1]=> 
    string(4) "more" 
    } 
} 
1

str_replace將適用於固定(已知)變量。要在{}中捕獲任何值,您必須使用正則表達式。

$content = "lorem ipsum {something} dolor sit amet."; 

$content = str_replace("{something}", "something else", $content); 

echo($content); 

// echos: lorem ipsum something else dolor sit amet. 
相關問題