我需要在每个数组值的开头添加一个<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 :(得分: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);
答案 1 :(得分: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]);
}