2
Example Text: This will be stored in the $_POST['x'] variable
This is sentence one.
This is sentence two.
This is sentence three.

If I run this code below It will return an array with only one element

$x= mysqli_real_escape_string($db, $_POST['x']);
$y= preg_split("/(\r\n|\n|\r)/", $x);

But if I run this code below it will split it correctly into all 3 elements.

$x = $_POST['x'];
$y= preg_split("/(\r\n|\n|\r)/", $x);

Has anyone else experienced this phenomenon? Why does it happen?

jakecraige
  • 2,707
  • 4
  • 21
  • 25

1 Answers1

4

http://php.net/mysqli-real-escape-string
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

This means newlines become \\n (LF), \\r (CR) and \\r\\n (CRLF). Therefore they no longer match the regex.

In future, RTM ;)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Ahh, That makes perfect sense. Somehow I missed that – jakecraige Feb 17 '13 at 22:00
  • @Constarr generally escape string would be the last function you call before concatenating the value with a mysql query. – datasage Feb 17 '13 at 22:10
  • Yeah I see why. Knowing this will probably help me avoid mistakes many times down the road. I'm surprised I even figured out what was going on now. Thanks! – jakecraige Feb 17 '13 at 22:24