+ All Categories
Home > Documents > Using PHP Strings

Using PHP Strings

Date post: 25-Dec-2015
Category:
Upload: juandelacruz
View: 25 times
Download: 4 times
Share this document with a friend
Description:
There are many PHP functions available for arrays and for strings.Topics:Formatting strings: trimming, for presentation, for storageJoining and splitting strings with string functionsComparing stringsMatching and replacing substrings with string functionsUsing regular expressions
22
PHP Using Strings 1
Transcript
Page 1: Using PHP Strings

PHP Using Strings

1

Page 2: Using PHP Strings

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

Page 3: Using PHP Strings

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

Page 4: Using PHP 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)

<<<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

Page 5: Using PHP Strings

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

Page 6: Using PHP Strings

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

Page 7: Using PHP Strings

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

Page 8: Using PHP Strings

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

Page 9: Using PHP Strings

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

Page 10: Using PHP Strings

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

Page 11: Using PHP Strings

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

Page 12: Using PHP Strings

nl2br.phphttp://www.nku.edu/~frank/csc301/Examples/

PHP_Strings/nl2br.phphttp://www.nku.edu/~frank/csc301/Examples/

PHP_Strings/nl2br_php.pdf

12

Page 13: Using PHP Strings

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

Page 14: Using PHP Strings

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

Page 15: Using PHP Strings

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

Page 16: Using PHP Strings

slasheshttp://www.nku.edu/~frank/csc301/Examples/

PHP_Strings/quotes.phphttp://www.nku.edu/~frank/csc301/Examples/

PHP_Strings/quotes_php.pdf

16

Page 17: Using PHP Strings

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

Page 18: Using PHP Strings

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

Page 19: Using PHP Strings

http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok.php

http://www.nku.edu/~frank/csc301/Examples/PHP_Strings/strtok_php.pdf

19

Page 20: Using PHP Strings

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

Page 21: Using PHP 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 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

Page 22: Using PHP 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

Comparing Strings

22


Recommended