PHP中的Preg_replace ...替换&标签之间的填充文本

时间:2011-08-14 21:01:22

标签: php regex preg-replace

这是我的代码:<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>

从$ text开始,然后preg_replace将运行。和$ text将放在:

<pre>$text</pre>

显示如下:

<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>

我试图使用:

$text=preg_replace("/<\/span>[a-zA-Z0-9\.\?\'\"\!\@\&\s\(\)\[\]\-\_\+\=]{8}\s+/","<br></span>$1$2",$text);

但结果是:

<span>C<br></span><span>F<br></span> ...

请帮我这个...&gt; _&lt;花上几个小时才能做到这一点,呃 如果有其他方式不使用preg_replace,请告诉我。

1 个答案:

答案 0 :(得分:1)

为了进一步参考,我想我可能会在使用PHP's DOM parser解决此任务时发布我想出的内容。

我可能会补充说,有点令人困惑的是,所有“真实”节点实际上都在NodeList中,而不是文档元素,而是文档元素的第一个子节点的NodeList(即 docElem - &gt;第一个孩子 - &gt;孩子而不是 docElement - &gt;孩子)。

<?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;
            }
    }

?>

这将输出:

f d
my text here lololol
t ok
dwa dawmo pgse gmspg mse
d

当然还有html元素:

<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>