将HTML段落转换为换行符


Convert HTML paragraph to newline

我正在为我的博客改进我的基本CMS。今天我添加了一个新函数,它将数据库中的(双)换行符转换为段落标记。

function nl2p($str) {
    $pattern = '/'n'n/';
    $replacement = '</p><p>';
    return preg_replace($pattern, $replacement, $str);
}

这工作得很好,除了我不想在我的<pre>标签中添加任何<p>标签。所以我想我会扩展我的函数来重新转换所有这些<p>标签到换行符,但它不起作用。知道为什么吗?

function nl2p($str) {
    $pattern = '/'n'n/';
    $replacement = '</p><p>';
    $par = preg_replace($pattern, $replacement, $str);
    preg_match_all('/'<pre'>(.*?)'<'/pre'>/', $par, $pre_content);
    return preg_replace($replacement, $pattern, $pre_content[0]);
}

Edit:由于这似乎是一个难以破解的坚果,也许我应该在我的代码中添加一些上下文。我在我的博客上使用语法高亮来显示原始格式的代码。荧光笔是用Javascript编写的,它利用HTML中预格式化的标记来显示代码。

同样,我上面的nl2p函数是我的blog类的一个方法。问题是它在我的预格式化标签中以原始格式(即可见)放置预格式化标签。

编辑2:下面是一些示例代码。首先是数据库中的原始代码,然后是格式化的HTML代码。另一个奇怪的细节是,下面代码中的最后一个</p>实际上在源代码中是不可见的。它出现在结束前标记之后。

<pre name="code" class="brush: javascript">
var data = [10, 20, 30];
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var circle = svg.selectAll("circle")
          .data(data)
          .enter()
            .append("circle")
            .attr("cx", function (d) { return d * 10; })
            .attr("cy", 50)
            .attr("r", function (d) { return d; })
            .style("fill", "red");</pre>
----------
var data = [10, 20, 30];<p></p><p>var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var circle = svg.selectAll("circle")
          .data(data)
          .enter()
            .append("circle")
            .attr("cx", function (d) { return d * 10; })
            .attr("cy", 50)
            .attr("r", function (d) { return d; })
            .style("fill", "red");</p>

假设您的regexp是ok的,它应该是:

return preg_replace($pattern,$replacement,$pre_content[1]);//note the second element of the array [1]

试试这个:

/**
 * Converts a new-line delimited string (with embedded HTML PRE tags) to
 * HTML paragraphs, preserving the newline delimiters within the PRE.
 * @param string $str
 * @return string
 */
function pFormat( $str )
{
    $a = explode( "'n", $str );
    $out = array();
    $isPre = FALSE;
    $lastBlank = FALSE;
    for( $i = 0, $l = count( $a ); $i < $l; $i++ )
    {
        $line = trim( $a[$i] );
        if( empty( $line ) )
        {
            if( $isPre )
            {
                $out[] = "";
            }
            continue;
        }
        if( substr( $line, 0, 4 ) == '<pre' )
        {
            $isPre = TRUE;
            $out[] = $line;
            continue;
        }
        if( substr( $line, 0, 5 ) == '</pre' )
        {
            $out[] = $line;
            $isPre = FALSE;
            continue;
        }
        $out = '<p>' . $line . '</p>';
    }
    return implode( "'n", $out );
}

按照要求,这应该将双换行符转换为段落标记,除了那些在预格式化标记中的双换行符:

$sourcestring="your source string";
echo preg_replace('#'n'n(?!((?!<pre>).)*</pre>)#is','</p><p>',$sourcestring);
在这里测试

,使用稍微修改的模式来解释换行字符,该工具包括:http://www.myregextester.com/?r=a24b18cf