By Adam Trachtenberg, David Sklar
Book Price: $44.99 USD
£31.99 GBP
PDF Price: $35.99
Cover | Table of Contents | Colophon
print 'I have gone to the store.'; print 'I\'ve gone to the store.'; print 'Would you pay $1.75 for 8 ounces of tap water?'; print 'In double-quoted strings, newline is represented by \n';
I have gone to the store. I've gone to the store. Would you pay $1.75 for 8 ounces of tap water? In double-quoted strings, newline is represented by \n
|
Escape sequence |
|---|
print 'I have gone to the store.'; print 'I\'ve gone to the store.'; print 'Would you pay $1.75 for 8 ounces of tap water?'; print 'In double-quoted strings, newline is represented by \n';
I have gone to the store. I've gone to the store. Would you pay $1.75 for 8 ounces of tap water? In double-quoted strings, newline is represented by \n
|
Escape sequence
|
|---|
@.<?php
if (strpos($_POST['email'], '@') === false) {
print 'There was no @ in the e-mail address!';
}
?>
false. If the
needle is at the beginning of the haystack,
strpos( ) returns 0, since position 0 represents
the beginning of the string. To differentiate between return values of 0
and false, you must use the identity operator
(===) or the not–identity operator
(!==) instead of regular equals
(==) or not-equals (!=). compares the return value from
strpos( ) to false using
===. This test only succeeds if strpos returns
false, not if it returns 0 or any other
number.http://www.php.net/strpos.<?php $substring = substr($string,$start,$length); $username = substr($_GET['username'],0,8); ?>
$start and $length are
positive, substr( ) returns
$length characters in the string, starting at
$start. The first character in the string is at
position 0. has positive
$start and $length.print substr('watch out for that tree',6,5);
out f
$length,
substr( ) returns the string from
$start to the end of the original string, as shown in
.print substr('watch out for that tree',17);
t tree
$start is bigger than the length of the
string, substr( ) returns
false..$start plus $length goes
past the end of the string, substr( ) returns all of
the string from $start forward, as shown in .print substr('watch out for that tree',20,5);
ree
$start is negative,
substr( ) counts back from the end of the string to
determine where your substring starts, as shown in .substr_replace(), as in .// Everything from position $start to the end of $old_string // becomes $new_substring $new_string = substr_replace($old_string,$new_substring,$start); // $length characters, starting at position $start, become $new_substring $new_string = substr_replace($old_string,$new_substring,$start,$length);
$length argument,
substr_replace( ) replaces everything from
$start to the end of the string. If
$length is specified, only that many characters are
replaced:print substr_replace('My pet is a blue dog.','fish.',12);
print substr_replace('My pet is a blue dog.','green',12,4);
$credit_card = '4111 1111 1111 1111';
print substr_replace($credit_card,'xxxx ',0,strlen($credit_card)-4);
My pet is a fish.
My pet is a green dog.
xxxx 1111
$start is negative, the new substring is
placed at $start characters counting from the end of
$old_string, not from the beginning:print substr_replace('My pet is a blue dog.','fish.',-9);
print substr_replace('My pet is a blue dog.','green',-9,4);
My pet is a fish.
My pet is a green dog.
$start and $length are 0,
the new substring is inserted at the start of
$old_string:print substr_replace('My pet is a blue dog.','Title: ',0,0);
Title: My pet is a blue dog.
for.
counts the vowels in a
string.<?php
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
if (strstr('aeiouAEIOU',$string[$i])) {
$vowels++;
}
}
?>
<?php
function lookandsay($s) {
// initialize the return value to the empty string
$r = '';
// $m holds the character we're counting, initialize to the first
// character in the string
$m = $s[0];
// $n is the number of $m's we've seen, initialize to 1
$n = 1;
for ($i = 1, $j = strlen($s); $i < $j; $i++) {
// if this character is the same as the last one
if ($s[$i] == $m) {
// increment the count of this character
$n++;
} else {
// otherwise, add the count and character to the return value
$r .= $n.$m;
// set the character we're looking for to the current one
$m = $s[$i];
// and reset the count to 1
$n = 1;
}
}
// return the built up string as well as the last count and character
return $r.$n.$m;
}
for ($i = 0, $s = 1; $i < 10; $i++) {
$s = lookandsay($s);
print "$s <br/>\n";
}
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211
<?php
print strrev('This is not a palindrome.');
?>
.emordnilap a ton si sihT
<?php
$s = "Once upon a time there was a turtle.";
// break the string up into words
$words = explode(' ',$s);
// reverse the array of words
$words = array_reverse($words);
// rebuild the string
$s = implode(' ',$words);
print $s;
?>
turtle. a was there time a upon Once
<?php
$reversed_s = implode(' ',array_reverse(explode(' ',$s)));
?>
http://www.php.net/strrev and
array_reverse( ) at http://www.php.net/array-reverse.<?php
$r = mysql_query("SELECT message FROM messages WHERE id = 1") or die();
$ob = mysql_fetch_object($r);
$tabbed = str_replace(' ',"\t",$ob->message);
$spaced = str_replace("\t",' ',$ob->message);
print "With Tabs: <pre>$tabbed</pre>";
print "With Spaces: <pre>$spaced</pre>";
?>
<?php
function pc_tab_expand($text) {
while (strstr($text,"\t")) {
$text = preg_replace_callback('/^([^\t\n]*)(\t+)/m','pc_tab_expand_helper', $text);
}
return $text;
}
function pc_tab_expand_helper($matches) {
$tab_stop = 8;
return $matches[1] .
str_repeat(' ',strlen($matches[2]) *
$tab_stop - (strlen($matches[1]) % $tab_stop));
}
$spaced = pc_tab_expand($ob->message);
?>
<?php
function pc_tab_unexpand($text) {
$tab_stop = 8;
$lines = explode("\n",$text);
foreach ($lines as $i => $line) {
// Expand any tabs to spaces
$line = pc_tab_expand($line);
$chunks = str_split($line, $tab_stop);
$chunkCount = count($chunks);
// Scan all but the last chunk
for ($j = 0; $j < $chunkCount - 1; $j++) {
$chunks[$j] = preg_replace('/ {2,}$/',"\t",$chunks[$j]);
}
// If the last chunk is a tab-stop's worth of spaces
// convert it to a tab; Otherwise, leave it alone
if ($chunks[$chunkCount-1] == str_repeat(' ', $tab_stop)) {
$chunks[$chunkCount-1] = "\t";
}
// Recombine the chunks
$lines[$i] = implode('',$chunks);
}
// Recombine the lines
return implode("\n",$lines);
}
$tabbed = pc_tab_unexpand($ob->message);
?><?php
print ucfirst("how do you do today?");
print ucwords("the prince of wales");
?>
How do you do today? The Prince Of Wales
print strtoupper("i'm not yelling!");
// Tags must be lowercase to be XHTML compliant
print strtolower('<A HREF="one.php">one</A>');
I'M NOT YELLING! <a href="one.php">one</a>
<?php
print ucfirst('monkey face');
print ucfirst('1 monkey face');
?>
Monkey face 1 monkey face
<?php
print ucwords('1 monkey face');
print ucwords("don't play zone defense against the philadelphia 76-ers");
?>
1 Monkey Face Don't Play Zone Defense Against The Philadelphia 76-ers
' and - aren’t
whitespace characters, <?php print 'You have '.($_REQUEST['boys'] + $_REQUEST['girls']).' children.'; print "The word '$word' is ".strlen($word).' characters long.'; print 'You owe '.$amounts['payment'].' immediately'; print "My circle's diameter is ".$circle->getDiameter().' inches.'; ?>
<?php print "I have $children children."; print "You owe $amounts[payment] immediately."; print "My circle's diameter is $circle->diameter inches."; ?>
$amounts['payment'] had to be written as
$amounts[payment] so it would be interpolated
properly. Use
curly braces around more complicated expressions to
interpolate them into a string. For example:<?php
print "I have less than {$children} children.";
print "You owe {$amounts['payment']} immediately.";
print "My circle's diameter is {$circle->getDiameter()} inches.";
?>
<?php
print <<< END
Right now, the time is
END
. strftime('%c') . <<< END
but tomorrow it will be
END
. strftime('%c',time() + 86400);
?>
<?php $zipcode = trim($_REQUEST['zipcode']); $no_linefeed = rtrim($_REQUEST['text']); $name = ltrim($_REQUEST['name']); ?>
<pre> tags, for example. If you are doing
comparisons with user input, you should trim the data first, so that
someone who mistakenly enters “98052” as their zip code isn’t forced to
fix an error that really isn’t one. Trimming before exact text
comparisons also ensures that, for example, “salami\n” equals “salami.”
It’s also a good idea to normalize string data by trimming it before
storing it in a database.<?php
// Remove numerals and space from the beginning of the line
print ltrim('10 PRINT A$',' 0..9');
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
?>
PRINT A$ SELECT * FROM turtles
$sales into a file.<?php
$sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
array('Northwest','2005-01-01','2005-02-01',546.33),
array('Southeast','2005-01-01','2005-02-01',93.26),
array('Southwest','2005-01-01','2005-02-01',945.21),
array('All Regions','--','--',1597.34) );
$fh = fopen('sales.csv','w') or die("Can't open sales.csv");
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die("Can't write CSV line");
}
}
fclose($fh) or die("Can't close sales.csv");
?>
php://output
, as shown in .<?php
$sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
array('Northwest','2005-01-01','2005-02-01',546.33),
array('Southeast','2005-01-01','2005-02-01',93.26),
array('Southwest','2005-01-01','2005-02-01',945.21),
array('All Regions','--','--',1597.34) );
$fh = fopen('php://output','w');
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die("Can't write CSV line");
}
}
fclose($fh);
?>
<?php
$fp = fopen('sample2.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp)) {
print '<tr>';
for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
print '<td>'.htmlentities($csv_line[$i]).'</td>';
}
print "</tr>\n";
}
print '</table>\n';
fclose($fp) or die("can't close file");
?>
,).
However, using a different delimiter somewhat defeats the purpose of CSV
as an easy way to exchange tabular data.<?php
$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
array('The Scarlatti Inheritance','Robert Ludlum',1971),
array('The Parsifal Mosaic','William Styron',1979) );
foreach ($books as $book) {
print pack('A25A15A4', $book[0], $book[1], $book[2]) . "\n";
}
?>
A25A14A4 tells
pack( ) to transform its subsequent arguments into
a 25-character space-padded string, a 14-character space-padded string,
and a 4-character space-padded string. For space-padded fields in
fixed-width records, pack( ) provides a concise
solution..-padded fields.<?php
$books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),
array('The Scarlatti Inheritance','Robert Ludlum',1971),
array('The Parsifal Mosaic','William Styron',1979) );
foreach ($books as $book) {
$title = str_pad(substr($book[0], 0, 25), 25, '.');
$author = str_pad(substr($book[1], 0, 15), 15, '.');
$year = str_pad(substr($book[2], 0, 4), 4, '.');
print "$title$author$year\n";
}
?>
<?php
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
$fields[1] = substr($s,0,10); // first field: first 10 characters of the line
$fields[2] = substr($s,10,5); // second field: next 5 characters of the line
$fields[3] = substr($s,15,12); // third field: next 12 characters of the line
// a function to do something with the fields
process_fields($fields);
}
fclose($fp) or die("can't close file");
?>
<?php
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
// an associative array with keys "title", "author", and "publication_year"
$fields = unpack('A25title/A14author/A4publication_year',$s);
// a function to do something with the fields
process_fields($fields);
}
fclose($fp) or die("can't close file");
?>
<?php $booklist=<<<END Elmer Gantry Sinclair Lewis1927 The Scarlatti InheritanceRobert Ludlum 1971 The Parsifal Mosaic Robert Ludlum 1982 Sophie's Choice William Styron1979 END; ?>
<?php
$books = explode("\n",$booklist);
for($i = 0, $j = count($books); $i < $j; $i++) {
$book_array[$i]['title'] = substr($books[$i],0,25);
$book_array[$i]['author'] = substr($books[$i],25,14);
$book_array[$i]['publication_year'] = substr($books[$i],39,4);
}
?><textarea>
form field.<?php
$words = explode(' ','My sentence is not very complicated');
?>
<?php
$words = split(' +','This sentence has some extra whitespace in it.');
$words = preg_split('/\d\. /','my day: 1. get up 2. get dressed 3. eat toast');
$lines = preg_split('/[\n\r]+/',$_REQUEST['textarea']);
?>
/i flag to
preg_split( ) for case-insensitive separator matching:<?php
$words = spliti(' x ','31 inches x 22 inches X 9 inches');
$words = preg_split('/ x /i','31 inches x 22 inches X 9 inches');
?>
<?php
$dwarves = 'dopey,sleepy,happy,grumpy,sneezy,bashful,doc';
$dwarf_array = explode(',',$dwarves);
?>
$dwarf_array a seven-element array,
so
print_r($dwarf_array) prints:Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy
[5] => bashful
[6] => doc
)
<?php
$dwarf_array = explode(',',$dwarves,5);
print_r($dwarf_array);
?>
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy,bashful,doc
)
<pre>/</pre> tags but have it stay within
a regularly sized browser window.<?php $s = "Four score and seven years ago our fathers brought forth↵ on this continent a new nation, conceived in liberty and↵ dedicated to the proposition that all men are created equal."; print "<pre>\n".wordwrap($s)."\n</pre>"; ?>
<pre> Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal. </pre>
<?php print wordwrap($s,50); ?>
Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal.
\n
can be used for line breaks. For double spacing, use
"\n\n":<?php print wordwrap($s,50,"\n\n"); ?>
Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal.
<?php
print wordwrap('jabberwocky',5);
print wordwrap('jabberwocky',5,"\n",1);
?>
jabberwocky jabbe rwock y
<?php
$packed = pack('S4',1974,106,28225,32725);
?>
<?php
$nums = unpack('S4',$packed);
?>
S4 tells
pack( ) to produce four unsigned short 16-bit
numbers in machine byte order from its input data. Given 1974, 106,
28225, and 32725 as input on a little-endian machine, this returns eight
bytes: 182, 7, 106, 0, 65, 110, 213, and 127. Each two-byte pair
corresponds to one of the input numbers: 7 * 256 + 182 is 1974; 0 * 256
+ 106 is 106; 110 * 256 + 65 = 28225; 127 * 256 + 213 = 32725.S4, the eight-byte sequence that
pack( ) produced returns a four-element array of
the original numbers. print_r($nums) prints:Array
(
[1] => 1974
[2] => 106
[3] => 28225
[4] => 32725
)
<?php
$nums = unpack('S4num',$packed);
print_r($nums);
?>
Array
(
[num1] => 1974
[num2] => 106
[num3] => 28225
[num4] => 32725
)
/ in unpack( ):<?php
$nums = unpack('S1a/S1b/S1c/S1d',$packed);
print_r($nums);
?>
SELECT query as CSV data and provides the correct
headers so that it is properly handled by the browser.<?php
require_once 'DB.php';
// Connect to the database
$db = DB::connect('mysql://david:hax0r@localhost/phpcookbook');
// Retrieve data from the database
$sales_data = $db->getAll('SELECT region, start, end, amount FROM sales');
// Open filehandle for fputcsv()
$output = fopen('php://output','w') or die("Can't open php://output");
$total = 0;
// Tell browser to expect a CSV file
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="sales.csv"');
// Print header row
fputcsv($output,array('Region','Start Date','End Date','Amount'));
// Print each data row and increment $total
foreach ($sales_data as $sales_line) {
fputcsv($output, $sales_line);
$total += $sales_line[3];
}
// Print total row and close file handle
fputcsv($output,array('All Regions','--','--',$total));
fclose($output) or die("Can't close php://output");
?>
Content-Type, tells the browser that the
output is not HTML, but CSV. The second header,
Content-Disposition, tells the browser not to display
the output but to attempt to load an external program to handle it. The
filename attribute of this header supplies a default
filename for the browser to use for the downloaded file.3/2 is 1.5, not
1, as it would be in some programming languages. PHP
also automatically converts from strings to numbers and back. For
instance, 1+"1" is 2.3/2 is 1.5, not
1, as it would be in some programming languages. PHP
also automatically converts from strings to numbers and back. For
instance, 1+"1" is 2.<?php
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric("05")) { /* true */ }
if (is_numeric('five')) { /* false */ }
if (is_numeric(0xDECAFBAD)) { /* true */ }
if (is_numeric("10e200")) { /* true */ }
?>
5 and the string 5 aren’t the same
in PHP. However, most of the time you won’t actually be concerned about
the distinction, which is why the behavior of
is_numeric( ) is useful.5.1; however, numbers with
thousands separators, such as 5,100, cause
is_numeric( ) to return
false.<?php is_numeric(str_replace($number, ',', '')); ?>
<?php
$delta = 0.00001;
$a = 1.00000001;
$b = 1.00000000;
if (abs($a - $b) < $delta) { /* $a and $b are equal */ }
?>
$a ==
$b, make sure the first number is within a very small amount
($delta) of the second one. The size of your delta
should be the smallest amount of difference you care about between two
numbers. Then use abs( ) to get the absolute value
of the difference.http://www.php.net/language.types.float.