2016-08-23 69 views
0

確實我有可能的字符串組合:檢查字符串中包含字符組合和替換,如果它在PHP

$string1 = '[variation-price] for product one.'; 
$string2 = 'Product two consists of [variation-parts]'; 
$string3 = 'Simple product'; 

$replace = 'Contains variations'; 

我需要檢查每一個字符串,如果它包含[variation-如果確實如此,更換整個字( fx [variation-price])與$replace

我已經嘗試過各種功能,打賭問題是我不知道確切地在字符串變異可能出現在哪裏或多久。

任何幫助或指導,非常感謝。

+1

http://php.net/preg_replace –

+1

'str_replace()函數'你檢查? – devpro

回答

3

使用正則表達式\[variation-.*?\]preg_replace()

preg_replace("/\[variation-.*?\]/", $replace, $string1) 

演示:https://ideone.com/MtNZ3L