2012-07-19 71 views
0

我知道這可能是一個常見問題,但我無法找到我想要的確切答案。兩個字符串之間的返回值

我有以下字符串。

#|First Name|# 
Random Text 
#|Last Name|# 

我希望做的是有一切都在#| & |#之間的值,並更換整個字符串的值。這必須在一個數組中,這樣我才能遍歷它們。

因此,作爲一個例子,我有:

#|First Name|# 

處理,我想它是後:

John 

所以主要的邏輯是使用的第一個name值打印出來自數據庫的價值。

有人可以幫我在這裏。

這是代碼,我已經試過:

preg_match('/#|(.*)|#/i', $html, $ret); 

感謝

+0

難道你不需要preg_match_all嗎? – Julio 2012-07-19 20:41:48

回答

1

你需要preg_replace_callback()爲此,除了讓你的正則表達式非貪婪和逃避豎條:

$replacements = array('John', 'Smith'); 
$index = 0; 
$output = preg_replace_callback('/#\|(.*?)\|#/i', function($match) use ($replacements, &$index) { 
    return $replacements[$index++];  
}, $input); 

will output

string(24) "John 
Random Text 
Smith" 
+0

回調參數對我來說是一個錯誤..'語法錯誤,意外的T_FUNCTION' – 2012-07-19 20:55:36

+0

@Sandeep - 您有一個不支持匿名函數的舊版PHP版本。 – nickb 2012-07-20 00:24:28

1
$string = '#|First Name|# 
Random Text 
#|Last Name|#'; 
$search = array(
    '#|First Name|#', 
    '#|Last Name|#', 
); 
$replace = array(
    'John', 
    'Smith', 
); 
$string = str_replace($search, $replace, $string); 
+0

+1如果事先知道所有的搜索,這是更高效的解決方案。 – nickb 2012-07-19 20:46:44

+0

謝謝你,但我需要一個正則表達式,因爲'First Name'和'Last Name'可以被命名爲別的東西,我不知道它會從自定義表中選出 – 2012-07-19 20:52:15

相關問題