tags:

views:

91

answers:

1

Why does this code run differently in CakePHP vs. a normal PHP file?

<?php
$data = "   One


Two

Three



Four";
$data = trim($data);
$data = preg_replace("/\n{2,}/", "\n", $data);
$data = explode("\n",$data);
var_dump($data);
?>

When I run this code in a normal PHP file, I get

array
  0 => string 'One' (length=3)
  1 => string 'Two' (length=3)
  2 => string 'Three' (length=5)
  3 => string 'Four' (length=4)

but if I run it from a Cake controller I get

Array
(
    [0] => one
    [1] => 
    [2] => 
    [3] => two
    [4] => 
    [5] => three
    [6] => 
    [7] => 
    [8] => 
    [9] => four
)
+2  A: 

There's nothing in Cake that would interfere with the behavior of native PHP functions. If you post the exact code you're using in Cake, including the action method definition, people will be better able to help you. My guess if you're doing something like this

public function myaction()
{
    $data = "   One


    Two

    Three



    Four";
    $data = trim($data);
    $data = preg_replace("/\n{2,}/", "\n", $data);
    $data = explode("\n",$data);
    var_dump($data);
}

Which means \n is never repeated more than once (there's additional whitespace after the \n. The bigger problem you're looking at is your regular expression isn't doing what you think it should when you run the code in Cake. Figure out why that is and you'll solve your problem. The following regular expression may prove more robust

$data = preg_replace("/[\r\n]\s{0,}/", "\n", $data);    
Alan Storm
i only copy paste code from this file to other file. But 2 result
meotimdihia
@meotim Is the code *left aligned in the first column*, or is it indented, i.e. are there **tabs** or **spaces** before the 'Two' and 'Three'?
deceze
your code is work
meotimdihia
but why in file normal localhost/test.php , my old code is valid ..
meotimdihia
@meotim If the text is indented, the indention is part of the text: ` One\n\t\t\n\t\t\n\t\tTwo\n\t\t\n\t\tThree...`, instead of just ` One\n\n\nTwo\n\nThree...`.
deceze
no, i only type enter while test, or only type enter in textarea,text is indented beacause i test trim($data)
meotimdihia
@meotim Can you copy your Cake test code into your question as well?
deceze
I code in file http://localhost/test.php is work => i copy it in controller cakePHP but it dont same result . Alan Storm 's code work in 2 file ,
meotimdihia
Trim only removes white space from the star and end of a string, not each line. If the 2nd regular expression worked for you, that means there was additional white space at the start of each line
Alan Storm