0

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';
echo '<br />';
}else{
echo 'Not code';
echo '<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. Please help me.

user1763032
  • 427
  • 9
  • 24

3 Answers3

2

nl2br doesn't generate <br /> unless you tell it to. Your explode logic is wrong.

Instead, try this:

$data = "Normal text.......";
foreach(explode("\n",$data) as $line) {
    // your existing foreach content code here
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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 />';
        }
?>
Puggan Se
  • 5,738
  • 2
  • 22
  • 48
0

You could also use "startsWith" as defined here...

https://stackoverflow.com/a/834355/2180189

...instead of the regexp match. That is, if the spaces are always at the beginning

Community
  • 1
  • 1
MightyPork
  • 18,270
  • 10
  • 79
  • 133