简体   繁体   中英

How to replace text outside html tags?

Here is my example:

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

How can i add all text outside tags, like this:

"<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>"
<?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);

?>

You can easily improve on that, but here is the basic:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM