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.

80 ” Strings And Patterns<br />

You can also specify an optional third parameter to strpos() to indicate that you<br />

want the search to start from a specific position within the haystack. For example:<br />

$haystack = ’123456123456’;<br />

$needle = ’123’;<br />

echo strpos ($haystack, $needle); // outputs 0<br />

echo strpos ($haystack, $needle, 1); // outputs 6<br />

i<br />

The strstr() function works similarly to strpos() in that it searches the haystack<br />

for a needle. The only real difference is that this function returns the portion of the<br />

haystack that starts with the needle instead of the latter’s position:<br />

$haystack = ’123456’;<br />

$needle = ’34’;<br />

echo strstr ($haystack, $needle); // outputs 3456<br />

In general, strstr() is slower than strpos()—therefore, you should use the latter if<br />

your only goal is to determine whether a certain needle occurs inside the haystack.<br />

Also, note that you cannot force strstr() to start looking for the needle from a given<br />

location by passing a third parameter.<br />

Both strpos() and strstr() are case sensitive and start looking for the needle from<br />

the beginning of the haystack. However, <strong>PHP</strong> provides variants that work in a caseinsensitive<br />

way or start looking for the needle from the end of the haystack. For<br />

example:<br />

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

// Case-insensitive search<br />

echo stripos(’Hello World’, ’hello’); // outputs zero<br />

echo stristr(’Hello My World’, ’my’); // outputs "My World"<br />

// Reverse search<br />

echo strrpos (’123123’, ’123’); // outputs 3

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

Saved successfully!

Ooh no, something went wrong!