i use nicEdit to write RTF data in my CMS. The problem is that it generates strings like this:
hello first line
this is a second line<
This approach will solve your problem:
<br>
or <br />
: you'll get an array of strings.<p>
.<br>
.</p><p>
.</p>
A different approach: using Regular Expressions
(<br ?/?>){2,}
Will match 2 or more <br>
. (See php.net on preg_split on how to do this.)
Now, the same approach on step 2 and 3: loop on the array twice, once from the beginning up (0..length) and once from the end down (length-1..0). If the entry is empty, remove it from the array. If the entry is not empty, quit the loop.
To do this:
$array = preg_split('/(<br ?/?>\s*){2,}/i', $string);
foreach($i = 0; $i < count($array); $i++) {
if($value == "") {
unset($array[$i]);
}else{
break;
}
}
foreach($i = count($array) - 1; $i >= 0; $i--) {
if($value == "") {
unset($array[$i]);
}else{
break;
}
}
$newString = '<p>' . implode($array, '</p><p>') . '</p>';
I think this should work for step #2 unless I am not understanding your scenario completely:
$string = str_replace( '<br><br>', '</p><p>', $string );
$string = str_replace( '<br /><br />', '</p><p>', $string );
$string = str_replace( '<br><br />', '</p><p>', $string );
$string = str_replace( '<br /><br>', '</p><p>', $string );
This will work even if the two <br>
s are on different lines (i.e. there is a newline or any whitespace between them):
function replace_br($data) {
$data = preg_replace('#(?:<br\s*/?>\s*?){2,}#', '</p><p>', $data);
return "<p>$data</p>";
}