如何替换html标签外的文字?

时间:2013-01-23 15:31:09

标签: php

以下是我的例子:

$content = "
<span class="1">One of </span>the major focuses for <span class = "2">vB 4.1.10 is</span> improving support...";

如何在标签外添加所有文字,如下所示:

"<span class="1">One of </span> <span class="3">the major focuses for</span> <span class = "2">vB 4.1.10 is</span> <span class="4">improving support...</span>"

2 个答案:

答案 0 :(得分:1)

<?php

$content = "abc<span class=\"1\">One of </span>the major focuses for <span class = \"2\">vB 4.1.10 is</span> improving support...";
$result = preg_replace("#>([^<>]+)<([^/]{1,1})#", '><span class="3">$1</span><$2', $content);
$result = preg_replace("#>([^<>]+)$#", '><span class="3">$1</span>', $result);
$result = preg_replace("#^([^<>]+)<([^/]{1,1})#", '<span class="3">$1</span><$2', $result);

var_dump($content);
var_dump($result);

?>

答案 1 :(得分:0)

你可以很容易地改进,但这里是基本的:

$content = "<span class=\"1\">One of </span>the major focuses for <span class = \"2\">vB 4.1.10 is</span> improving support...";
$parts = preg_split("!(<span[^>]*>[^>]*<\/span>)!", $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $key => $val) {
    if (!empty($val)) {
        echo (substr($val, 0, 1) != '<') ? '<span>'.$val.'</span>' : $val;
    }
}