php strtok()

// string strtok(string input, string separator);
<?php

/*
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
*/

    $string = "This is /tan example /nstring";
    $tok = strtok($string, "/n/t ");
    while($tok){
        echo "Word = $tok/n";
        var_dump($tok);
        $tok = strtok('/n/t '); //Note it's not strtok("/n/t ")
    }
/*
Output:

Word = This
string(4) "This"
Word = is
string(2) "is"
Word =  a
string(2) "     a"  // WHY???
Word = example
string(7) "example"
Word =               //WHY???
s
string(2) "
s"
Word = ri
string(2) "ri"
Word = g
string(1) "g"
*/

/*
The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:
*/

# Old strtok() behavior
    $first_token = strtok('/something', '/');
    $second_token = strtok('/');
    var_dump($first_token, $second_token);
/*
Output:

string(0) ""
    string(9) "something"
*/

# New strtok() behavior
    $first_token = strtok('/something', '/');
    $second_token = strtok('/');
    var_dump($first_token, $second_token);
/*
Output:

string(9) "something"
    bool(false)
*/

?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章