为什么在CakePHP中使用正则表达式(必须是CakePHP)

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("/
{2,}/", "
", $data);
$data = explode("
",$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
)

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("/
{2,}/", "
", $data);
    $data = explode("
",$data);
    var_dump($data);
}

Which means is never repeated more than once (there's additional whitespace after the . 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("/[
]\s{0,}/", "
", $data);