String Functions
Advertisements

PHP strtok() Function

Topic: PHP String ReferencePrev|Next

Description

The strtok() function splits a string into smaller strings (tokens).

The following table summarizes the technical details of this function.

Return Value: Returns a string token.
Version: PHP 4+

Syntax

The basic syntax of the strtok() function is given with:

strtok(string, split);

The following example shows the strtok() function in action.

<?php
// Sample string
$str = "Mary had\ta little\nlamb";

// Using space, tab and newline as tokenizing characters
$tok = strtok($str, " \t\n");

// Printing tokens
while($tok !== false){
    echo "$tok<br>";
    $tok = strtok(" \t\n");
}
?>

Note: Only the first call to strtok() uses the string argument. Every subsequent call to strtok only needs the split argument, because it keeps track of where it is in the current string. To tokenize a new string, call strtok() with the string argument again.


Parameters

The strtok() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to split.
split Required. Specifies one or more characters to be used when splitting up the string.

More Examples

Here're some more examples showing how strtok() function actually works:

The following example shows the behavior of this function when an empty part found.

<?php
// Sample string
$str = "/products";

// Tokenizing string using forward slash character
$first_token  = strtok($str, "/");
$second_token = strtok("/");

// Displaying info about tokens
var_dump($first_token, $second_token);
?>
Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties