php函数nl2p忽略以方括号

时间:2017-07-08 01:23:48

标签: php regex text-processing

我有一个正在运行的功能但无法找到根据我的需要修改它的方法。

功能:

function mynl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '',     $string);
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),

trim($string)).'</p>';
}

处理的示例数据:

    [img]2700:800[/img]

    Some text that is separated with linebreaks in the database and should   be put inside <i>paragraph</i>.
    Sometimes single break can exist and should not be made into new paragraph.
    [quote]
    [img]right:2701:350[/img]
    <b>This is</b>: yet another text for proper paragraph.
    [/quote]

处理后的预期结果:

    [img]2700:800[/img]

    <p>Some text that is separated with linebreaks in the database and should be put inside <i>paragraph</i>.
    Sometimes single break can exist and should not be made into new paragraph.</p>
    [quote]
    [img]right:2701:350[/img]
    <p><b>This is</b>: yet another text for proper paragraph.</p>
    [/quote]

请注意,示例中的所有中断和新行都是为了解释函数可以找到的不同变体。

方括号内可以存在许多自定义标签,而它看起来与bbcode非常接近。

1 个答案:

答案 0 :(得分:0)

由于您要求忽略以括号开头或结尾的行, 如果该行包含括号,为什么不尝试首先找到?

if (strpos($lines, "]") !== false) //for lines that has ]
//proceed to next line
else 
//do process here

如果你想检查一行的开头是[,最后是],请先尝试爆炸,

$str = explode("",$line); //notice that nothing is inside the double qoute
if($str[0] == '[' && $str[$str.length-1] == ']')
//proceed to next line
else 
//do process here