2012-12-04 136 views
-1

我需要在每個數組值的開始處添加一個<p>標記,並在每個數組值的末尾添加一個關閉</p>標記。替換數組中的值

如果有[]分隔符,然後他們需要與<p class="myclass">

Array 
(
    [0] => [This is a line of text 
    [1] => and another 
    [2] => and yet another.] [This is another line of text 
    [3] => and another 
    [4] => and another] [OK, so you get the idea. 
) 

代替上述陣列應該成爲:

Array 
(
    [0] => <p class="myclass">This is a line of text</p> 
    [1] => <p>and another</p> 
    [2] => <p>and yet another.</p> <p class="myclass">This is another line of text</p> 
    [3] => <p>and another</p> 
    [4] => <p>and another</p> <p class="myclass">OK, so you get the idea.</p> 
) 

的問題是:使用foreach循環,如何我從第一個數組到第二個數組?

+0

你的問題非常混亂,正是你想做的事? –

回答

1
for($i = 0; $i < count($array); $i++) { 
    $array[$i] = '<p>'.$array[$i].'</p>'; 
    $array[$i] = preg_replace('/\]/', '</p>', $array[$i]); 
    $array[$i] = preg_replace('/\[/', '<p class="myclass">', $array[$i]); 
    $array[$i] = preg_replace('/<p><p/', '<p', $array[$i]); 
} 

See Live Example

+1

謝謝!這工作完美。我很難讓這個工作正確。 – NaN

+0

非常歡迎。我活着服務:) – Maritim

3
$myArray = array(
    '[This is a line of text', 
    'and another', 
    'and yet another.] [This is another line of text', 
    'and another', 
    'and another] [OK, so you get the idea.', 
); 

array_walk($myArray,'pTagger'); 

function pTagger(&$value) { 
    $value = str_replace(array('[',']'),array('<p class="myClass">','</p>'),$value); 
    if (substr($value,0,2) !== '<p') $value = '<p>' . $value; 
    if (substr($value,-4) !== '</p>') $value .= '</p>'; 
} 

var_dump($myArray); 
+0

謝謝馬克的答案! – NaN