phpregexnewline

preg_match() not matching start of line after splitting nl2br() string by <br />


I have the following code:

$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach ($data as $value) {
    if (preg_match('/^&nbsp&nbsp&nbsp&nbsp/', $value)) {
        echo 'code<br />';
    } else {
        echo 'Not code<br />';
    }
}

I want to check if each of the lines starts with 4 spaces and if it does I want to echo as 'Code' and if it doesn't I want to echo as 'Not code'. But I am getting the output as 'Not code' though the 2nd, 3rd and 4th lines start with four spaces. I cannot figure out what I have done wrong.


Solution

  • got it working added a trim() to get rid of the newline in front of the string

    nl2br replace \n with <br />\n (or <br />\r\n), so when spliting on <br /> the \n is left as the first char

    <?php
            $data = "Normal text
    &nbsp&nbsp&nbsp&nbspcode
    &nbsp&nbsp&nbsp&nbspcode
    &nbsp&nbsp&nbsp&nbspcode
    Normal text";
    
            $data = nl2br($data);
    
            $data= explode('<br />', $data );
    
            foreach($data as $value)
            {
                    if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/', trim($value)))
                    {
                            echo 'code';
                    }
                    else
                    {
                            echo 'Not code';
                    }
                    echo '<br />';
            }
    ?>