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.

Comparing Strings<br />

119<br />

The length parameter can be used to specify either a number of characters to return<br />

(if it is positive) or the end character of the return sequence (if it is negative). For<br />

example,<br />

substr($test, 0, 4);<br />

returns the first four characters of the string—namely, Your.The code<br />

echo substr($test, 5, -13);<br />

returns the characters between the fourth character <strong>and</strong> the thirteenth-to-last<br />

character—that is, customer service.The first character is location 0. So location 5 is<br />

the sixth character.<br />

Comparing Strings<br />

So far, we’ve just shown you how to use == to compare two strings for equality.You can<br />

do some slightly more sophisticated comparisons using <strong>PHP</strong>.We’ve divided these comparisons<br />

into two categories for you: partial matches <strong>and</strong> others.We deal with the others<br />

first <strong>and</strong> then get into partial matching, which we need to further develop the Smart<br />

Form example.<br />

Performing String Ordering: strcmp(), strcasecmp(), <strong>and</strong><br />

strnatcmp()<br />

The strcmp(), strcasecmp(), <strong>and</strong> strnatcmp() functions can be used to order strings.<br />

This capability is useful when you are sorting data.<br />

The prototype for strcmp() is<br />

int strcmp(string str1, string str2);<br />

The function expects to receive two strings, which it compares. If they are equal, it will<br />

return 0. If str1 comes after (or is greater than) str2 in lexicographic order, strcmp()<br />

will return a number greater than zero. If str1 is less than str2, strcmp() will return a<br />

number less than zero.This function is case sensitive.<br />

The function strcasecmp() is identical except that it is not case sensitive.<br />

The function strnatcmp() <strong>and</strong> its non–case sensitive twin, strnatcasecmp() compare<br />

strings according to a “natural ordering,” which is more the way a human would do<br />

it. For example, strcmp() would order the string 2 as greater than the string 12 because<br />

it is lexicographically greater. strnatcmp() would order them the other way around.You<br />

can read more about natural ordering at http://www.naturalordersort.org/

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

Saved successfully!

Ooh no, something went wrong!