ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 在标记中包装字符串的每个字母,避免使用HTML标记

2019-08-30 00:29:10  阅读:171  来源: 互联网

标签:html php regex word-wrap preg-replace


我想构建一个函数,它接受一个字符串并将其每个字母包装在< 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标签似乎错了?

解决方法:

您可以考虑使用DOMDocument解析HTML并仅包含DOMText节点值内的字符.请参阅代码中的注释.

// Define source
$source = 'H&iuml; <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>

标签:html,php,regex,word-wrap,preg-replace
来源: https://codeday.me/bug/20190829/1764718.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有