2012-12-04 4 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