13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

118 Chapter 4 String Manipulation <strong>and</strong> Regular Expressions<br />

strtok() is typically used as follows:<br />

$token = strtok($feedback, ‘“ “);<br />

echo $token.””;<br />

while ($token != “”) {<br />

$token = strtok(“ “);<br />

echo $token.””;<br />

}<br />

As usual, it’s a good idea to check that the customer actually typed some feedback in<br />

the form, using, for example, the empty() function.We have omitted these checks for<br />

brevity.<br />

The preceding code prints each token from the customer’s feedback on a separate<br />

line <strong>and</strong> loops until there are no more tokens. Empty strings are automatically skipped in<br />

the process.<br />

Using substr()<br />

The substr() function enables you to access a substring between given start <strong>and</strong> end<br />

points of a string. It’s not appropriate for the example used here but can be useful when<br />

you need to get at parts of fixed format strings.<br />

The substr() function has the following prototype:<br />

string substr(string string, int start[, int length] );<br />

This function returns a substring copied from within string.<br />

The following examples use this test string:<br />

$test = ‘Your customer service is excellent’;<br />

If you call it with a positive number for start (only), you will get the string from the<br />

start position to the end of the string. For example,<br />

substr($test, 1);<br />

returns our customer service is excellent. Note that the string position starts<br />

from 0, as with arrays.<br />

If you call substr() with a negative start (only), you will get the string from the<br />

end of the string minus start characters to the end of the string. For example,<br />

substr($test, -9);<br />

returns excellent.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!