05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

echo("The last comma in the record is at position $pos");<br />

The last comma in the record is at position 18<br />

If you pass a string as the second argument to strrpos( ), only the first character is<br />

searched for. To find the last occurrence of a multicharacter string, reverse the<br />

strings and use strpos( ):<br />

$long = "Today is the day we go on holiday to Florida";<br />

$to_find = "day";<br />

$pos = strpos(strrev ($long), strrev($to_find));<br />

if ($pos === false) {<br />

echo("Not found");<br />

} else {<br />

// $pos is offset into reversed strings<br />

// Convert to offset into regular strings<br />

$pos = strlen($long) - $pos - strlen($to_find);;<br />

echo("Last occurrence starts at position $pos");<br />

}<br />

Last occurrence starts at position 30<br />

Searches returning rest of string<br />

The strstr( ) function finds the first occurrence of a small string in a larger string<br />

and returns from that small string on. For instance:<br />

$record = "Fred,Flintstone,35,Wilma";<br />

$rest = strstr($record, ","); // $rest is ",Flintstone,35,Wilma"<br />

The variations on strstr( ) are:<br />

stristr( )<br />

Case-insensitive strstr( )<br />

strchr( )<br />

Alias for strstr( )<br />

strrchr( )<br />

Find last occurrence of a character in a string<br />

As with strrpos( ), strrchr( ) searches backward in the string, but only for a character,<br />

not for an entire string.<br />

Searches using masks<br />

If you thought strrchr( ) was esoteric, you haven’t seen anything yet. The strspn( )<br />

and strcspn( ) functions tell you how many characters at the beginning of a string<br />

are comprised of certain characters:<br />

$length = strspn(string, charset);<br />

For example, this function tests whether a string holds an octal number:<br />

function is_octal ($str) {<br />

return strspn($str, '01234567') == strlen($str);<br />

}<br />

94 | Chapter 4: Strings<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!