220 likes | 391 Views
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.
E N D
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. • (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)
Strings • Topics: • Formatting strings: trimming, for presentation, for storage • Joining and splitting strings with string functions • Comparing strings • Matching and replacing substrings with string functions • Using regular expressions
Strings • 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) <<<DONE your_string_here on_multiple_lines_until closing_identifier DONE • or nowdoc syntax • Interpolation of variables in double-quoted and heredoc strings • The string concatenation operator, “.“
Formatting Strings - trimming • Several functions are available to tidy up strings before using them – especially user strings from an HTML form interface • Trimming strings = removing any excess whitespace • string 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 $str Use 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 - printing • 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 formattedand 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 - printf • The functions printf() and sprintf () provide a means for formatting strings • They will be familiar to C programmers • They are a bit “messy” and we will cover only briefly for a few basic capabilities • printf() is used to format and then print a string • Just use as printf(….); • sprintf() formats into a new string rather than printing it • Use as $newStr = sprintf(….);
Formatting Strings - printf • Both subroutines take a format string and a list of variablesprintf($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 string • you 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 • The format specifications (or conversion specifications): • Start with the % character • An 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 • Example: to format for currency • Data type is “float” (f) • Number of digits before decimal point is 5 • Number of digits after decimal point is 2 • Format 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 – presentation • HTML formatting: string nl2br(string $str) • Replaces all the new line characters in $str with XHTML <br /> tags • Creates a new string • Useful when echoing a long string to the browser • Example: $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 />
nl2br.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/nl2br.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/nl2br_php.pdf
Formatting Strings – presentation • Changing the case of a string: • string strtoupper (string $str) – turns string to uppercase • string strtolower (string $str) – turns string to lowercase • string ucfirst (string $str) – capitalizes 1st character of the string if it’s alphabetic • string 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 string • Function creates a new string
Formatting Strings – for storage • Reason – certain characters • are 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, backslash • Solution: 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 • Before applying addslashes() check if magic_quotes_gpc configuration directive is turned on • With magic_quotes_gpc on, all variables coming from GET, POST and cookie are automatically escaped applying addslashes() would cause double-escaping • boolean get_magic_quotes_gpc() returns T if magic_quotes_gpc is on; F otherwise • phpinfo() displays magic_quotes_gpc directive’s value, among other information • magic_quotes_gpc is currently off on cscdb
slashes • http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/quotes.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/quotes_php.pdf
Joining & splitting strings with string functions • array explode (string $separator, string $input [, int $limit]) • Splits $input into pieces on a specified $separator string • Pieces are returned in an array • The number of pieces can be limited to $limit. • Example: $email = ‘campana1@nku.edu’; $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 $glue • join() is identical to implode()
Joining & splitting strings with string functions • string strtok(string $input, string $separator) • Gets tokens (pieces) from $input one at a time • Splits $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 parameters while ($token != "") { echo "$token <br />"; $token = strtok(" ,."); }
http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok.phphttp://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok_php.pdf
Joining & splitting strings with string functions • 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 string • Called with 1 negative argument (start): returns the substring of $str from the end of the string - |$start| characters to the end of the string • Called 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
Comparing Strings • 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 order • Returns >0 if $str2 sorts before $str1 in lexicographic order • Returns 0 if $str1 and $str2 are the same in lexicographic order • strcmp(…) is case-sensitive
Comparing Strings • 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