25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

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

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

Strings And Patterns ” 83<br />

The third argument is our starting point—the space in the first example; the function<br />

replaces the contents of the string from here until the end of the string with the<br />

second argument passed to it, thus resulting in the output Hello Reader. You can<br />

also pass an optional fourth parameter to define the end of the substring that will<br />

be replaced (as shown in the second example, which outputs Canned potatoes are<br />

good).<br />

Combining substr_replace() with strpos() can prove to be a powerful tool. For<br />

example:<br />

$user = "davey@php.net";<br />

$name = substr_replace($user, "", strpos($user, ’@’);<br />

echo "Hello " . $name;<br />

By using strpos() to locate the first occurrence of the @ symbol, we can replace the<br />

rest of the e-mail address with an empty string, leaving us with just the username,<br />

which we output in greeting.<br />

Extracting Substrings<br />

The very flexible and powerful substr() function allows you to extract a substring<br />

from a larger string. It takes three parameters: the string to be worked on, a starting<br />

index and an optional length. The starting index can be specified as either a positive<br />

integer (meaning the index of a character in the string starting from the beginning)<br />

or a negative integer (meaning the index of a character starting from the end). Here<br />

are a few simple examples:<br />

$x = ’1234567’;<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

echo substr ($x, 0, 3); // outputs 123<br />

echo substr ($x, 1, 1); // outputs 2<br />

echo substr ($x, -2); // outputs 67<br />

echo substr ($x, 1); // outputs 234567<br />

echo substr ($x, -2, 1); // outputs 6

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

Saved successfully!

Ooh no, something went wrong!