Parsing a string with strtok()

PHP/MySQL
Last Updated: 2007-02-25 13:17:11
STEP 1: Tokenizing
You can parse a string with strtok() which is a function that requires two arguments; the string to be parsed and the delimiters by which to split the string.

strtok stands for "string tokenizing". You can tokenize a string with as many delimiters as you would like. Unlike explode() where the delimiter you set is combined to make one delimiter, strtok "tokenizes" upon the first successful token found. strtok() returns false when reaching the end of the string.

In this example we will use strtok() to parse out the query string of a URL.

<?php
$URL = "http://www.joelucky39.com/index.php?page=1&action=post&pass=0";
$tokens = "?&";
$stringQuery = strtok($URL, $tokens);
while (is_string($stringQuery)) {
if ($stringQuery) {
print "$stringQuery<br>";
}
$stringQuery = strtok($tokens);
}
?>


This would print out:
http://www.joelucky39.com/index.php
page=1
action=post
pass=0

Back to Tutorial List

This is the JoeLucky39 tutorial section. Feel free to use whatever information you find here on your own site(s). Know that not all tutorials are ideal for all sites, so feel free to modify the information contained in this tutorail section as best suits your web site.

At JoeLucky39 you can find tutorials on Comic Art, PHP/MySQL, and more are added all the time. So, visit often and feel free to contact Joe if you think that his tutorials need to be changed or updated.

Joe believes in the open source movement and is happy to share his knowledge with anyone who asks. All Joe asks is, if you use Joe's open source tutorials, you share your knowledge as well.
Thank you and I hope you find what you are looking for. If not feel free to contact me and ask.
LOG IN:
© Copywrite 2010 JoeLucky39.com