2016-03-08 151 views
1

我有一個正則表達式,發現在兩個方括號中的文字:(PHP)替換字符串數組值

preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches); 

從一個陣列稱爲row我需要在關鍵的值與正則表達式匹配,並將其替換爲$body字符串。

例如,

foreach ($matches[0] as $array_key) { 
    row->$array_key; 
    //The value at the specific key, but I need to take this value and put it back in the spot where its key was found in the body string 

} 
+0

任何例如字符串和預期輸出經過一些事情的問題聽起來不清楚看起來你正在尋找'preg_repace' –

+0

是否有任何代碼 – WowThatsLoud

+0

'行 - > $ array_key;'看起來你正在處理對象,而不是數組。顯示'$ body'和'row'的示例輸入內容 – RomanPerekhrest

回答

0

試試這個:

$body = '[testtext][othertext]'; 
preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches); 

foreach($matches[0] as $key => $value) 
{ 
    $values[] = $value; 
} 
print_r($values); 

結果是:

Array ([0] => testtext [1] => othertext) 

這是你想要的嗎?

0

,這是爲我工作

<pre> 
    <?php 
    $b = "Name: some sample text [] and some other [] and the thired one [] and 4 [] putting it on end[] and some thing after"; 
    preg_match_all("/(?<=\[).+?(?=\])/", $b, $m); 

    $str = substr($b, 0,strpos($b, '[')+1); 

    $row= array("val1","val2","val3","val4","val5"); 

    foreach($row as $k => $value) { 

     $afterstr = ( $k <= count($m[0])-1) ? $m[0][$k] : ""; // because the last ']' is not in $m array so we have to handle that 
     $str .= $value . $afterstr ; 
    } 

    $str .= strrchr($b,']'); // appending after the last ']' text 
    var_dump($str); 

柱(135)「名稱:一些示例文本[VAL1]和其他一些[VAL2]和thired一個[VAL3] 4 [VAL4]把它?在結束[val5]和