开发者

PHP explode() function issue

开发者 https://www.devze.com 2022-12-21 05:50 出处:网络
Please help me out on this explode() function issue. I am getting unexpected results for the third scenario, what\'s the explanation?

Please help me out on this explode() function issue. I am getting unexpected results for the third scenario, what's the explanation?

EDIT: The value $page_string is actually from the database. This time I did the tests using var_dump instead of ec开发者_如何学编程ho. The strings, How does php count them? How is "15&page" count 11?

var_dump($page_string);//string(11) "15&page"

1. Pop out ampersand ... fine.

    $page_id_array = explode("&",$page_string);
    $page_id = $page_id_array[0]; 
    var_dump($page_id); 
    // string(2) "15"

2. Pop out number ... fine

    $page_id_array = explode("15",$page_string);
    $page_id = $page_id_array[1]; 
    var_dump($page_id); 
    //string(9) "&blog"

3. Pop out '&page' ... why?

     $page_id_array = explode("&page",$page_string);
     $page_id = $page_id_array[0]; 
     var_dump($page_id); 
     //string(11) "15&page"
     var_dump($page_id_array[1]);
     //NULL

EDIT: After answer and comments from jasonbar I did the test which confirms his answer:

     $page_id_array = explode("&page",$page_string);
     $page_id = $page_id_array[0]; 
     var_dump($page_id); 
     //string(2) "15"


I think my comment seems a likely explanation. I tried out your code using "15&page" as the test string and it explodes properly using '&page' as the delimiter.

Make sure the & isn't actually encoded as &

You could try print_r'ing the array you get back from explode() to see if thats really the case. If so you would end up with 15, amp;page when exploding on just '&'.


I've run the following with PHP5. Can you provide a complete script? What version of PHP are you running?

$page_string = "15&page";

$page_id_array = explode("&",$page_string);
var_dump($page_id_array);
// array has 2 values, 15 and page
$page_id = $page_id_array[0]; 
echo '<br/>'.$page_id.'<br/>'; 

$page_id_array = explode("15",$page_string);
var_dump($page_id_array);
// array has 2 values, <empty> and &page
$page_id = $page_id_array[0]; 
echo '<br/>'.$page_id.'<br/>'; 

$page_id_array = explode("&page",$page_string);
var_dump($page_id_array);
// array has 2 values, 15 and <empty>
$page_id = $page_id_array[0]; 
echo '<br/>'.$page_id.'<br/>'; 


The last scenario also passed for me, there's something about your string that is causing the anomaly.

0

精彩评论

暂无评论...
验证码 换一张
取 消