Upload
izzy
View
116
Download
10
Embed Size (px)
DESCRIPTION
PHP Using Strings. Note. There are many PHP functions available for arrays and for strings. You will only be responsible for those presented in class. You may use others you find in PHP references for your homework assignments. - PowerPoint PPT Presentation
Citation preview
PHP Using Strings
1
There are many PHP functions available for arrays and for strings.
You will only be responsible for those presented in class.You may use others you find in PHP references for your
homework assignments.(http://www.php.net/string - string type,
http://us2.php.net/manual/en/ref.strings.php - string functions, http://us2.php.net/manual/en/book.pcre.php - Perl-compatible regular expressions)
Note
2
Strings
Topics:Formatting strings: trimming, for presentation, for storageJoining and splitting strings with string functionsComparing stringsMatching and replacing substrings with string functionsUsing regular expressions
3
Recall:String literals:
delimited by double or single quotes, in heredoc syntax (creates a large text string without needing quotes,
and can be used anyplace a string would go)
<<<DONEyour_string_hereon_multiple_lines_untilclosing_identifier DONE
or nowdoc syntax
Interpolation of variables in double-quoted and heredoc strings The string concatenation operator, “.“
Strings
4
Several functions are available to tidy up strings before using them – especially user strings from an HTML form interface
Trimming strings = removing any excess whitespacestring trim(string $str [, string $charlist])
Strips whitespace (spaces, newlines \n, carriage returns \r, horizontal tabs \t, end-of-string characters \0) from the start and end of string $strUse the second optional parameter to indicate a list of characters to strip instead of the default list (=whitespace)Creates new string!
ltrim(…) and rtrim(…) are similar to trim(), but remove whitespace only from the start /left (ltrim) or end/right (rtrim) of the string
Ex: collecting feedback for Bob’s auto parts → clean the user input, trimming it is a first step
Formatting Strings - trimming
5
3 basic methods:language construct echo
Prints a comma-separated series of strings Can enclose string in parentheses for single string only
language construct print Prints a single string – which can be enclosed in parentheses or not Returns T/F to indicate if it was successful
function printf( ) – formats and prints a string Just like C printf First argument is a format string, the rest are variables to be formatted
and interpolated; see next The sprintf() function is similar, except that it returns the formatted
string instead of printing it to the browser
All printing is output to the browser.
Formatting Strings - printing
6
The functions printf() and sprintf () provide a means for formatting stringsThey will be familiar to C programmersThey are a bit “messy” and we will cover only briefly for a
few basic capabilities
printf() is used to format and then print a stringJust use as printf(….);
sprintf() formats into a new string rather than printing itUse as $newStr = sprintf(….);
Formatting Strings - printf
7
Both subroutines take a format string and a list of variables printf($fmt_str, $a, $b, $c, …);
The format string contains:characters to be printed as they are and special characters to describe how the following variables are to be
interpolated (= substituted) into the format stringyou can format several variables into a printf() by including several
format specifications, (normally) one for each variable specified:→ the format specifications should be in the same number as the variables to format → the ith format specification is applied to the ith variable
Formatting Strings - printf
8
The format specifications (or conversion specifications): Start with the % characterAn optional “–” indicates the data in the field is left-justified
(rather than right-justified, which is the default)Letters are used to designate the data type to be printed (floating
point value - f, decimal number - d, string - s, character - c, etc.)Numbers between the % and the format type character give field
sizes: First number is total size (width), Second number (if any) gives the number of decimal places to display
(precision), Numbers separated by a period.
Q: %10s, %6d, %5.2f ?
Formatting Strings - printf
9
Example: to format for currencyData type is “float” (f)Number of digits before decimal point is 5Number of digits after decimal point is 2Format specification is %8.2d
printf(“Your total is \$%8.2f\n”, $total);
If $total is 123.4567, prints “Your total is $123.46”Example:
printf(“%4d and %5.3f”, $a, $b);If $a is 1.23 and $b is 4.56, prints “1 and 4.560”
There are far too many options to describe them all here.Read your textbook or review your Java text for more details
Formatting Strings - printf
10
HTML formatting: string nl2br(string $str) Replaces all the new line characters in $str with XHTML <br /> tagsCreates a new stringUseful when echoing a long string to the browserExample:
$sfweather = “<p><strong>San Francisco daily weather forecast</strong>: \n
Today: \n Partly cloudy. Highs from the 60s to mid 70s. West winds 5 to 15 mph. \n
Tonight: \n Increasing clouds. Lows in the mid 40s to lower 50s. West winds 5 to 10 mph.</p>”;
echo $sfweather; // the browser disregards plain whitespace
// everything on a single line except for newlines forced by the browser window
echo nl2br($sfweather); // each newline character is replaced with <br />
Formatting Strings – presentation
11
nl2br.phphttp://www.nku.edu/~frank/csc301/Examples/
PHP_Strings/nl2br.phphttp://www.nku.edu/~frank/csc301/Examples/
PHP_Strings/nl2br_php.pdf
12
Changing the case of a string:string strtoupper (string $str) – turns string to uppercasestring strtolower (string $str) – turns string to lowercasestring ucfirst (string $str) – capitalizes 1st character of the string
if it’s alphabeticstring ucwords(string $str) – sets 1st character in each word that
begins with an alphabetic character to upper case
For each of these functions: The argument is a stringFunction creates a new string
Formatting Strings – presentation
13
Reason – certain charactersare valid as part of a string but can cause problems when are inserted into a database because are
interpreted by the DBMS as control characters
Ex: single and double quotation marks, backslashSolution: escape those characters by adding a backslash in
front of them: ” → \”, \ → \\how: string addslashes(string $str) returns the reformatted $str
string Conversely:
string stripslashes(string $str) returns a copy of the $str string from which the escape characters have been removed
Formatting Strings – for storage
14
Before applying addslashes() check if magic_quotes_gpc configuration directive is turned onWith magic_quotes_gpc on, all variables coming from GET, POST and
cookie are automatically escaped
applying addslashes() would cause double-escapingboolean get_magic_quotes_gpc()
returns T if magic_quotes_gpc is on; F otherwisephpinfo()
displays magic_quotes_gpc directive’s value, among other informationmagic_quotes_gpc is currently off on cscdb
Formatting Strings – for storage
15
slasheshttp://www.nku.edu/~frank/csc301/Examples/
PHP_Strings/quotes.phphttp://www.nku.edu/~frank/csc301/Examples/
PHP_Strings/quotes_php.pdf
16
array explode (string $separator, string $input [, int $limit])Splits $input into pieces on a specified $separator stringPieces are returned in an arrayThe number of pieces can be limited to $limit.Example:
$email = ‘[email protected]’;$email_array = explode(‘@’, $email);// email_array[0] contains the username (campana1)// email_array[1] contains the domain name (nku.edu)// actions can be decided upon customer’s origin as indicated by the domain name
string implode (string $glue, array $pieces) → opposite to explode()Joins array elements from $pieces with string $gluejoin() is identical to implode()
Joining & splitting strings with string functions
17
string strtok(string $input, string $separator)Gets tokens (pieces) from $input one at a timeSplits $input on each of the characters in $separator rather than on the
whole separator (as explode() does)Usage:
// first token extracted with a call to strtok() with both parameters $token = strtok($feedback, " ,.");
// subsequent calls automatically apply to the same string; // only separator is passed to strtok()// strtok() maintains its internal pointer to its current place in the string// reset the pointer by calling again strtok() with two parameterswhile ($token != "") {
echo "$token <br />";$token = strtok(" ,.");
}
Joining & splitting strings with string functions
18
http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok.php
http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok_php.pdf
19
string substr(string $str, int $start[, int $length])Called with 1 positive argument (start): returns the substring of $str
from the $start position to the end of the stringCalled with 1 negative argument (start): returns the substring of $str
from the end of the string - |$start| characters to the end of the stringCalled with 2 arguments (start and length):
If $length is positive: specifies the number of characters to return starting from position $start
If $length is negative: function returns the substring from $start position to the end of the string - |$length | position
Note: string position starts at 0
Extracting a single character: $string{$index}$index is 0-based character count from start of string
Joining & splitting strings with string functions
20
Use == and === for exact compare
Use strcmp(…) for ordered compare: int strcmp(string $str1, string $str2)Returns <0 if $str1 sorts before $str2 (= $str1 is less than
$str2) in lexicographic orderReturns >0 if $str2 sorts before $str1 in lexicographic orderReturns 0 if $str1 and $str2 are the same in lexicographic orderstrcmp(…) is case-sensitive
Comparing Strings
21
strncmp(… ) Similar to strcmp(…), Has 3rd argument: number of characters to compare (if < strings’
length)
Use int strlen(string $str) to get the length of a string
Comparing Strings
22