0

I have a function that is working but can not figure a way to modify it for my needs.

Function:

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>';
}

Example data that is processed:

    [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]

Desired result after processing:

    [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]

Please note that all breaks and new lines in the examples are given on purpose to explain the different variants the function can find.

There are many custom tags that can exist inside the square brackets and while it looks close to bbcode it is not.

Papa Zhi
  • 45
  • 1
  • 11

1 Answers1

0

Since you are asking to ignore the lines that start or ends with brackets, why not try to find first if the line contains brackets?

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

if you want to check if the line has [ at the beginning and ] at the end try to explode the line first,

$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
Rence
  • 124
  • 7
  • I have the same idea about the processing logic, however i would like to do it with regex so that it is elegant. – Papa Zhi Jul 08 '17 at 08:02