我想构建一个函数,它接受一个字符串并将其每个字母包装在<span>
中,除了空格和HTML标记(在我的例子中,<br>
标记)。
所以:
"Hi <br> there."
......应该成为
"<span>H</span><span>i</span> <br> <span>t</span><span>h</span><span>e</span><span>r</span><span>e</span><span>.</span>"
我没有运气想出自己的解决方案,所以我环顾四周,发现我很难找到我想要的东西。
我找到的最接近的是Neverever的回答here。
然而,它似乎没有那么好用,因为<br>
标签的每个字符都包含在<span>
中,并且它与éèàï等强调字符不匹配。
我该如何处理? 为什么用正则表达式解析HTML标签似乎错了?
答案 0 :(得分:2)
您可以尝试类似......
<?php
$str = "Hi <br> there.";
$newstr = "";
$notintag = true;
for ($i = 0; $i < strlen($str); $i++) {
if (substr($str,$i,1) == "<") {
$notintag = false;
}
if (($notintag) and (substr($str,$i,1) != " ")) {
$newstr .= "<span>" . substr($str,$i,1) . "</span>";
} else {
$newstr .= substr($str,$i,1);
}
if (substr($str,$i,1) == ">") {
$notintag = true;
}
}
echo $newstr;
?>
答案 1 :(得分:2)
您可以使用([^\s>])(?!(?:[^<>]*)?>)
正则表达式获得结果。要启用Unicode支持,只需将其与u
选项一起使用:
<?php
$re = "/([^\\s>])(?!(?:[^<>]*)?>)/u";
$str = "Hi <br> there.";
$subst = "<span>$1</span>";
$result = preg_replace($re, $subst, $str);
echo $result;
?>
您可以在这里找到regex explanation and demo。
请参阅sample program,不支持Unicode,此处为one with Unicode support(区别在于u
选项)。
答案 2 :(得分:1)
您可以考虑使用DOMDocument来解析HTML并在DOMText个节点的值中仅包含字符。请参阅代码中的注释。
// Define source
$source = 'Hï <br/> thérè.';
// Create DOM document and load HTML string, hinting that it is UTF-8 encoded.
// We need a root element for this so we wrap the source in a temporary <div>.
$hint = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$dom = new DOMDocument();
$dom->loadHTML($hint . "<div>" . $source . "</div>");
// Get contents of temporary root node
$root = $dom->getElementsByTagName('div')->item(0);
// Loop through children
$next = $root->firstChild;
while ($node = $next) {
$next = $node->nextSibling; // Save for next while iteration
// We are only interested in text nodes (not <br/> etc)
if ($node->nodeType == XML_TEXT_NODE) {
// Wrap each character of the text node (e.g. "Hi ") in a <span> of
// its own, e.g. "<span>H</span><span>i</span><span> </span>"
foreach (preg_split('/(?<!^)(?!$)/u', $node->nodeValue) as $char) {
$span = $dom->createElement('span', $char);
$root->insertBefore($span, $node);
}
// Drop text node (e.g. "Hi ") leaving only <span> wrapped chars
$root->removeChild($node);
}
}
// Back to string via SimpleXMLElement (so that the output is more similar to
// the source than would be the case with $root->C14N() etc), removing temporary
// root <div> element and space-only spans as well.
$withSpans = simplexml_import_dom($root)->asXML();
$withSpans = preg_replace('#^<div>|</div>$#', '', $withSpans);
$withSpans = preg_replace('#<span> </span>#', ' ', $withSpans);
echo $withSpans, PHP_EOL;
输出:
<span>H</span><span>ï</span> <br/> <span>t</span><span>h</span><span>é</span><span>r</span><span>è</span><span>.</span>