BUY THIS BOOK
Add to Cart

Print Book $44.99


Add to Cart

Print+PDF $58.49

Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £31.99

What is this?

Looking to Reprint or License this content?


PHP Cookbook
PHP Cookbook, Second Edition By Adam Trachtenberg, David Sklar
August 2006
Pages: 810

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Strings
Strings in PHP are sequences of bytes, such as “We hold these truths to be self-evident” or “Once upon a time” or even “111211211.” When you read data from a file or output it to a web browser, your data are represented as strings.
PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.
Usually, PHP strings are ASCII strings. You must do extra work to handle non-ASCII data like UTF-8 or other multibyte character encodings, see .
Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes , and with the “here document” (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself. shows four single-quoted strings.
Example . Single-quoted strings
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';
prints:
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
Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
Double-quoted strings don’t recognize escaped single quotes, but they do recognize interpolated variables and the escape sequences shown in .
Table 1-1: Double-quoted string escape sequences
Escape sequence
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Strings in PHP are sequences of bytes, such as “We hold these truths to be self-evident” or “Once upon a time” or even “111211211.” When you read data from a file or output it to a web browser, your data are represented as strings.
PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.
Usually, PHP strings are ASCII strings. You must do extra work to handle non-ASCII data like UTF-8 or other multibyte character encodings, see .
Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes , and with the “here document” (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself. shows four single-quoted strings.
Example . Single-quoted strings
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';
prints:
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
Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
Double-quoted strings don’t recognize escaped single quotes, but they do recognize interpolated variables and the escape sequences shown in .
Table 1-1: Double-quoted string escape sequences
Escape sequence
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Substrings
You want to know if a string contains a particular substring. For example, you want to find out if an email address contains a @.
Use strpos(  ) , as in .
Example . Finding a substring with strpos(  )
<?php

if (strpos($_POST['email'], '@') === false) {
    print 'There was no @ in the e-mail address!';
 }

?>
The return value from strpos(  ) is the first position in the string (the “haystack”) at which the substring (the “needle”) was found. If the needle wasn’t found at all in the haystack, strpos(  ) returns 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.
Documentation on strpos(  ) at http://www.php.net/strpos.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Extracting Substrings
You want to extract part of a string, starting at a particular place in the string. For example, you want the first eight characters of a username entered into a form.
Use substr(  ) to select your substring, as in .
Example . Extracting a substring with substr(  )
<?php
$substring = substr($string,$start,$length);
$username = substr($_GET['username'],0,8);
?>
If $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.
Example . Using substr(  ) with positive $start and $length
print substr('watch out for that tree',6,5);
prints:
out f
If you leave out $length, substr(  ) returns the string from $start to the end of the original string, as shown in .
Example . Using substr(  ) with positive start and no length
print substr('watch out for that tree',17);
prints:
t tree
If $start is bigger than the length of the string, substr(  ) returns false..
If $start plus $length goes past the end of the string, substr(  ) returns all of the string from $start forward, as shown in .
Example . Using substr(  ) with length past the end of the string
print substr('watch out for that tree',20,5);
prints:
ree
If $start is negative, substr(  ) counts back from the end of the string to determine where your substring starts, as shown in .
Example . Using substr(  ) with negative start
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Replacing Substrings
You want to replace a substring with a different string. For example, you want to obscure all but the last four digits of a credit card number before printing it.
Use substr_replace(‏‎‎), as in .
Example . Replacing a substring with substr_replace(  )
// 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);
Without the $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
If $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.
If $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.
The function substr_replace(  ) is useful when you’ve got text that’s too big to display all at once, and you want to display some of the text with a link to the rest. displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Processing a String One Byte at a Time
You need to process each byte in a string individually.
Loop through each byte in the string with for. counts the vowels in a string.
Example . Processing each byte 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++;
    }
}
?>
Processing a string a character at a time is an easy way to calculate the “Look and Say” sequence, as shown in .
Example . The “Look and Say” sequence
<?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";
}
prints:
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
It’s called the “Look and Say” sequence because each element is what you get by looking at the previous element and saying what’s in it. For example, looking at the first element, 1, you say “one one.” So the second element is “11.” That’s two ones, so the third element is “21.” Similarly, that’s one two and one one, so the fourth element is “1211,” and so on.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reversing a String by Word or Byte
You want to reverse the words or the bytes in a string.
Use strrev(  ) to reverse by byte, as in .
Example . Reversing a string by byte
<?php
print strrev('This is not a palindrome.');
?>
prints:
.emordnilap a ton si sihT
To reverse by words, explode the string by word boundary, reverse the words, and then rejoin, as in .
Example . Reversing a string by word
<?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;
?>
prints:
turtle. a was there time a upon Once
Reversing a string by words can also be done all in one line with the code in .
Example . Concisely reversing a string by word
<?php
$reversed_s = implode(' ',array_reverse(explode(' ',$s)));
?>
discusses the implications of using something other than a space character as your word boundary; documentation on strrev(  ) at http://www.php.net/strrev and array_reverse(  ) at http://www.php.net/array-reverse.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expanding and Compressing Tabs
You want to change spaces to tabs (or tabs to spaces) in a string while keeping text aligned with tab stops. For example, you want to display formatted text to users in a standardized way.
Use str_replace(  ) to switch spaces to tabs or tabs to spaces, as shown in .
Example . Switching tabs and spaces
<?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>";
?>
Using str_replace(  ) for conversion, however, doesn’t respect tab stops. If you want tab stops every eight characters, a line beginning with a five-letter word and a tab should have that tab replaced with three spaces, not one. Use the pc_tab_expand(  ) function shown in into turn tabs to spaces in a way that respects tab stops.
Example . pc_tab_expand(  )
<?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);
?>
You can use the pc_tab_unexpand(  ) function shown in to turn spaces back to tabs.
Example . pc_tab_unexpand(  )
<?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);
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Controlling Case
You need to capitalize, lowercase, or otherwise modify the case of letters in a string. For example, you want to capitalize the initial letters of names but lowercase the rest.
Use ucfirst(  ) or ucwords(  ) to capitalize the first letter of one or more words, as shown in .
Example . Capitalizing letters
<?php
print ucfirst("how do you do today?");
print ucwords("the prince of wales");
?>
prints:
How do you do today?
The Prince Of Wales
Use strtolower(  ) or strtoupper(  ) to modify the case of entire strings, as in .
Example . Changing case of strings
print strtoupper("i'm not yelling!");
// Tags must be lowercase to be XHTML compliant
print strtolower('<A HREF="one.php">one</A>');
prints:
I'M NOT YELLING!
<a href="one.php">one</a>
Use ucfirst(  ) to capitalize the first character in a string:
<?php
print ucfirst('monkey face');
print ucfirst('1 monkey face');
?>
This prints:
Monkey face
1 monkey face
Note that the second phrase is not “1 Monkey face.”
Use ucwords(  ) to capitalize the first character of each word in a string:
<?php
print ucwords('1 monkey face');
print ucwords("don't play zone defense against the philadelphia 76-ers");
?>
This prints:
1 Monkey Face
Don't Play Zone Defense Against The Philadelphia 76-ers
As expected, ucwords(  ) doesn’t capitalize the “t” in “don’t.” But it also doesn’t capitalize the “e” in “76-ers.” For ucwords(  ), a word is any sequence of nonwhitespace characters that follows one or more whitespace characters. Since both ' and - aren’t whitespace characters,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interpolating Functions and Expressions Within Strings
You want to include the results of executing a function or expression within a string.
Use the string concatenation operator (.), as shown in , when the value you want to include can’t be inside the string.
Example . String concatenation
<?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.';
?>
You can put variables, object properties, and array elements (if the subscript is unquoted) directly in double-quoted strings:
<?php
print "I have $children children.";
print "You owe $amounts[payment] immediately.";
print "My circle's diameter is $circle->diameter inches.";
?>
Interpolation with double-quoted strings places some limitations on the syntax of what can be interpolated. In the previous example, $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.";
?>
Direct interpolation or using string concatenation also works with heredocs. Interpolating with string concatenation in heredocs can look a little strange because the closing heredoc delimiter and the string concatenation operator have to be on separate lines:
<?php
print <<< END
Right now, the time is 
END
. strftime('%c') . <<< END
 but tomorrow it will be 
END
. strftime('%c',time() + 86400);
?>
Also, if you’re interpolating with heredocs, make sure to include appropriate spacing for the whole string to appear properly. In the previous example,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Trimming Blanks from a String
You want to remove whitespace from the beginning or end of a string. For example, you want to clean up user input before validating it.
Use ltrim(  ), rtrim(  ), or trim(  ). ltrim(  ) removes whitespace from the beginning of a string, rtrim(  ) from the end of a string, and trim(  ) from both the beginning and end of a string:
<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>
For these functions, whitespace is defined as the following characters: newline, carriage return, space, horizontal and vertical tab, and null.
Trimming whitespace off of strings saves storage space and can make for more precise display of formatted data or text within <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.
The trim(  ) functions can also remove user-specified characters from strings. Pass the characters you want to remove as a second argument. You can indicate a range of characters with two dots between the first and last characters in the range:
<?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;',';');
?>
This prints:
PRINT A$
SELECT * FROM turtles
PHP also provides chop(  )
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating Comma-Separated Data
You want to format data as comma-separated values (CSV) so that it can be imported by a spreadsheet or database.
Use the fputcsv(  ) function to generate a CSV-formatted line from an array of data. writes the data in $sales into a file.
Example . Generating comma-separated data
<?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");

?>
To print the CSV-formatted data instead of writing it to a file, use the special output stream php://output , as shown in .
Example . Printing comma-separated data
<?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);
?>
To put the CSV-formatted data into a string instead of printing it or writing it to a file, combine the technique in with output buffering, as shown in .
Example . Putting comma-separated data into a string
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parsing Comma-Separated Data
You have data in comma-separated values (CSV) format—for example, a file exported from Excel or a database—and you want to extract the records and fields into a format you can manipulate in PHP.
If the CSV data is in a file (or available via a URL), open the file with fopen(  ) and read in the data with fgetcsv(  ) . prints out CSV data in an HTML table.
Example . Reading CSV data from a file
<?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");
?>
In PHP 4, you must provide a second argument to fgetcsv(  ) that is a value larger than the maximum length of a line in your CSV file. (Don’t forget to count the end-of-line whitespace.) In PHP 5 the line length is optional. Without it, fgetcsv(  ) reads in an entire line of data. (Or, in PHP 5.0.4 and later, you can pass a line length of 0 to do the same thing.) If your average line length is more than 8,192 bytes, your program may run faster if you specify an explicit line length instead of letting PHP figure it out.
You can pass fgetcsv(  ) an optional third argument, a delimiter to use instead of a comma (,). However, using a different delimiter somewhat defeats the purpose of CSV as an easy way to exchange tabular data.
Don’t be tempted to bypass fgetcsv(  ) and just read a line in and explode(  ) on the commas. CSV is more complicated than that, able to deal with field values that have, for example, literal commas in them that should not be treated as field delimiters. Using
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating Fixed-Width Field Data Records
You need to format data records such that each field takes up a set amount of characters.
Use pack(  ) with a format string that specifies a sequence of space-padded strings. transforms an array of data into fixed-width records.
Example . Generating fixed-width field data records
<?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";
}

?>
The format string 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.
To pad fields with something other than a space, however, use substr(  ) to ensure that the field values aren’t too long and str_pad(  ) to ensure that the field values aren’t too short. transforms an array of records into fixed-width records with .⁠-⁠padded fields.
Example . Generating fixed-width field data records without pack(  )
<?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";
}

?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parsing Fixed-Width Field Data Records
You need to break apart fixed-width records in strings.
Use substr(  ) as shown in .
Example . Parsing fixed-width records with substr(  )
<?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");
?>
Or unpack(  ) , as shown in .
Example . Parsing fixed-width records with unpack(  )
<?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");
?>
Data in which each field is allotted a fixed number of characters per line may look like this list of books, titles, and publication dates:
<?php
$booklist=<<<END
Elmer Gantry             Sinclair Lewis1927
The Scarlatti InheritanceRobert Ludlum 1971
The Parsifal Mosaic      Robert Ludlum 1982
Sophie's Choice          William Styron1979
END;
?>
In each line, the title occupies the first 25 characters, the author’s name the next 14 characters, and the publication year the next 4 characters. Knowing those field widths, you can easily use substr(  ) to parse the fields into an
<?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);
}
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Taking Strings Apart
You need to break a string into pieces. For example, you want to access each line that a user enters in a <textarea> form field.
Use explode(  ) if what separates the pieces is a constant string:
<?php
$words = explode(' ','My sentence is not very complicated');
?>
Use split(  ) or preg_split(  ) if you need a POSIX or Perl-compatible regular expression to describe the separator:
<?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']);
?>
Use spliti(  ) or the /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');
?>
The simplest solution of the bunch is explode(  ). Pass it you

Return to PHP Cookbook