this is my code: <span>C</span> <span>F</span> <span>D</span> Hello, this is a text from me. Song's lyric, I need to fix <span>D </span> <span>E</span>
its wil from $text, and then preg_replace will run. and $text will be place in:
<pre>$text</pre>
To show like this:
<span>C</span> <span>F</span> <span>D</span>
Hello, this is a text from me. Song's lyric, I need to fix
<span>D</span> <span>E</span>
I tried to use:
$text=preg_replace("/<\/span>[a-zA-Z0-9\.\?\'\"\!\@\&\s\(\)\[\]\-\_\+\=]{8}\s+/","<br></span>$1$2",$text);
But the resul开发者_运维技巧t is:
<span>C<br></span><span>F<br></span> ...
Please help me on this one... >_< spend like hours to do it, hic If have another way not use preg_replace, please show me too.
For further reference I figured I might post what I came up with when solving this task using PHP's DOM parser.
I might add it was somewhat confusing that all the "real" nodes are in fact in the NodeList of not the document element, but the NodeList of the first child of the document element (that is docElem -> first child -> children instead of docElement -> children).
<?php
$str = '<span>f</span> <span>d</span> my text here lololol <span>t</span> <span>ok</span> dwa dawmo pgse gmspg mse <span>d</span>';
$doc = new DOMDocument();
$doc->loadHTML($str);
$docElem = $doc->documentElement;
$children = $docElem->childNodes->item(0)->childNodes;
for ($i = 0, $len = $children->length; $i<$len; $i++)
{
$node = $children->item($i);
$val = trim($node->nodeValue);
// text
if (is_a($node, 'DOMText') && $val) {
echo "<br />\r\n" . $val . "<br />\r\n";
// span
} else if ($node->tagName == 'span') {
echo '<'. $node->tagName .'>' . $val . '</'. $node->tagName .'>';
// whitespace
} else {
echo $node->nodeValue;
}
}
?>
This will output:
f d
my text here lololol
t ok
dwa dawmo pgse gmspg mse
d
of course with the html elements as well:
<span>f</span> <span>d</span><br />
my text here lololol<br />
<span>t</span> <span>ok</span><br />
dwa dawmo pgse gmspg mse<br />
<span>d</span>
精彩评论