2017-07-08 58 views
0

我有一个正在工作的函数,但无法找到一种方法来修改它以满足我的需要。php函数nl2p忽略以方括号开头或结尾的行

功能:被处理

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则不是。

回答

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 
+0

我对处理逻辑同样的想法,但是我想用正则表达式来做,所以它很优雅。 – Zhi

相关问题