我想构建一个函数,它接受一个字符串,并将其每个字母包装在<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的答案。
然而,它似乎没有那么好用,因为<br>
标签的每个字符都被包裹在一个<span>
中,并且它与强调字符(如éiï)不匹配。
我该如何处理?为什么用正则表达式解析HTML标签看起来如此错误?
您可以使用([^'s>])(?!(?:[^<>]*)?>)
正则表达式来实现结果。要启用Unicode支持,只需将其与u
选项一起使用即可:
<?php
$re = "/([^''s>])(?!(?:[^<>]*)?>)/u";
$str = "Hi <br> there.";
$subst = "<span>$1</span>";
$result = preg_replace($re, $subst, $str);
echo $result;
?>
在这里,您可以找到regex的解释和演示。
请参阅不支持Unicode的示例程序,这里有一个支持Unicode的程序(区别在于u
选项)。
您可以考虑使用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>
你可以试试。。。
<?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;
?>