【问题标题】:Replace spaces with   between PRE tags用 PRE 标记之间的空格替换
【发布时间】:2011-07-16 07:01:13
【问题描述】:

我需要扩展以下代码 sn-p 的功能,以仅在包含 html 的字符串中的 PRE 标记之间转换空格:

str_replace(' ',' ',$str);

例如,如果 $str 包含以下字符串;

<p>abc 123</p>
<pre class="abc" id="123">abcedfg 12345</pre>

它将被转换为:

<p>abc 123</p>
<pre class="abc" id="123">abcedfg&nbsp;12345</pre>

类似的;

<p>abc 123</p>
<pre>abcedfg 12345</pre>

将转换为:

<p>abc 123</p>
<pre>abcedfg&nbsp;12345</pre>

【问题讨论】:

    标签: php regex


    【解决方案1】:

    您可以使用 DOM 解析器。以下是使用 PHP 原生 DOM 函数的方法:

    <?php
    $test = '
    <p>abc 123</p>
    <pre class="abc" id="pre123">abcedfg 12345</pre>
    <p>abc 123</p>
    <pre class="abc" id="pre456">abcedfg 12345</pre>
    <div>
        <div>
            <div>
                <pre class="abc" id="pre789">abcedfg 12345</pre>
            </div>
        </div>
    </div>
    ';
    $dom = new DOMDocument("1.0");
    $dom->loadHTML($test);
    $xpath = new DOMXpath($dom);
    $pre = $xpath->query("//pre");
    foreach($pre as $e) {
        $e->nodeValue = str_replace(" ", "&nbsp;", $e->nodeValue);
    }
    echo $dom->saveHTML();
    

    输出

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><body><p>abc 123</p>
    <pre class="abc" id="pre123">abcedfg&nbsp;12345</pre>
    <p>abc 123</p>
    <pre class="abc" id="pre456">abcedfg&nbsp;12345</pre>
    <div>
        <div>
            <div>
                <pre class="abc" id="pre789">abcedfg&nbsp;12345</pre>
            </div>
        </div>
    </div></body></html>
    

    编辑:

    我不确定如何摆脱 doctype/html/body 标记。适用于 PHP >= 5.3.6 的一种可能解决方案是在 saveHTML() 方法中指定要输出的节点。其他可能性是使用我一开始就避免使用的正则表达式。

    【讨论】:

    • 谢谢萨尔曼。我会根据你的回答重新整理我的问题。
    • Righto,我提出了一个新问题stackoverflow.com/questions/6716486/… 请随时继续那里的 DOM 解析器解决方案,我也不知道如何删除 doctype/html/body 标签。我确实有PHP >= 5.3.6
    • 它看起来比 RegEx 更“干净”,但除此之外,似乎没有必要为了一个相对简单的操作而开始弄乱 DOM
    • @graham:我注意到我的回答中的缺点,因此我已经发布了关于你其他问题的更新答案。
    【解决方案2】:
    $text = '<pre>test 1234 123</pre>';
    $text2 = '<pre class="test">test 1234 123</pre>';
    
    function testreplace($text) {
        return preg_replace_callback('/[\<]pre(.*)[\>](.*)[\<]\/pre[\>]/i', 
            create_function(
                '$matches',
                'return "<pre".$matches[1].">".str_replace(" ", "&nbsp;", $matches[2])."</pre>\n";'
            ), $text);
    }
    
    echo testreplace($text);
    echo testreplace($text2);
    

    花了我一段时间......但它有效。

    【讨论】:

    • @henasraf:请粘贴您的代码,不要转义 html 特殊字符。然后选择您的代码并使用编辑器中的代码格式按钮{ }
    • @SalmanA 啊,我明白了:P 是的,这给了我一些问题来粘贴在这里哈哈@Graham 是的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2020-08-29
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多