MCIS/UA. String Literals. String Literals. Here Documents The <<< operator (also known as heredoc) can be used to construct multi-line strings.

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "MCIS/UA. String Literals. String Literals. Here Documents The <<< operator (also known as heredoc) can be used to construct multi-line strings."

Transcription

1 MCIS/UA PHP Training 2003 Chapter 6 Strings String Literals Single-quoted strings Double-quoted strings escape sequences String Literals Single-quoted \' - single quote \\ - backslash Interpreted items variables \n \r \t \\ \$ \" \nnn \xnn Double-quoted - value of variable - new line - return - tab - backslash - dollar sign - double quote - ASCII char in octal - ASCII char in hex heredoc Here Documents The <<< operator also known as heredoc) can be used to construct multi-line strings. $mystring = <<< End This is a multi-line string. This is the second line. This is the third line. End; print $mystring; This is a multi-line string. This is the second line. This is the third line.

2 Here Documents $name = $info->queryfirstcolumn "SELECT name ". "FROM info ". "WHERE uniqueid =?", $uid); $sql = <<< end_of_sql SELECT name FROM info WHERE uniqueid =? end_of_sql; $name = $info->queryfirstcolumn$sql, $uid); Here Documents $name = $info->queryfirstcolumn<<< end_of_sql SELECT name FROM info WHERE uniqueid =? end_of_sql, $uid); outputting Outputting strings Several ways to output strings and other data: echo print printf sprintf print_r var_dump echo and print echo and print echo and print output data and are pretty much identical $x = "abc"; echo "value: $x"; value: abc print "value: $x"; value: abc printf

3 printf printf outputs formatted data $x = 5; printf"value: %d", $x); value: 5 $mon = 4; $day = 8; $year = 2003; printf"%d/%d/%d", $mon, $day, $year); 4/8/2003 format codes printf Format Codes format result input output %% %d %f %s %b %c %o %x %X %u percent sign integer floating point string binary character octal hex lowercase) hex uppercase) unsigned integer abc % abc 101 A bcd15 75BCD modifiers printf Additional modifiers may be added between the % and the letter in the following order) 0 - do zero padding rather than space padding minus sign - forces left-justification number - minumum number of characters to output; for floats - number of digits before the decimal point.number - for floats, the number of decimal digits modifier examples printf printf"%5d", 3); printf"%-5d", 3); 3 3 printf"%05d", 3); printf"%8f", 3.5); printf"%8.3f", 3.5); printf"%08.3f", 3.5);

4 printf $mon = 4; $day = 8; $year = 2003; printf"%d/%d/%d", $mon, $day, $year); 4/8/2003 printf"%02d/%02d/%04d", $mon, $day, $year); 04/08/2003 sprintf sprintf sprintf formatted data and returns a string $x = sprintf"%05d", 3); print $x; print_r print_r print_r can be used to dump variables $x = array1, "abc", array"covertka" => "Kent", "kingmatm" => "Tim")); print_r$x); [0] => 1 [1] => abc [2] => [covertka] => Kent [kingmatm] => Tim ) ) var_dump var_dump var_dump can also be used to dump variables $x = array1, "abc", array"covertka" => "Kent", "kingmatm" => "Tim")); var_dump$x); array3) { [0]=> int1) [1]=> string3) "abc" [2]=> array2) { ["covertka"]=> string4) "Kent" ["kingmatm"]=> string3) "Tim" } } string functions

5 Useful string functions There are many functions that can be used to manipulate strings: strlen) - string length trim), ltrim), rtrim) - trim strings strtoupper), strtolower) - change case ucfirst), ucwords) - uppercases the first character or first character of all words of a string Useful string functions substr) - returns part of a string strpos) - finds a substring within string explode) - splits a string into parts based on a seperator - returns an array implode) - concatenates all of the elements of an array together separated by a character Useful string functions str_repeat) - used to repeat a string a number of times str_pad - pads a string with another string to a particular length left, right, or both) strcasecmp) - compares 2 strings ignoring case parse_url) - parses a URL into it's parts scheme, host, port, path, etc.) Useful string functions htmlentities), htmlspecialchars) - encodes html special characters < > & ' ", etc.) rawurlencode), rawurldecode), urlencode), urldecode) - encodes a URL regular expressions

6 Regular Expressions preg_match'/\d\d\d-\d\d\d\d/', $phone); preg_match'/\d\d\d-)?\d\d\d-\d\d\d\d/', $phone); 513) or 513) preg_match'/\?\d\d\d-)?\)?\s?\d\d\d-\d\d\d\d/', $phone); parse the parts into variables preg_match'/\?\d\d\d)?-?\)?\s?\d\d\d)-\d\d\d\d)/', $phone, $parts); Regular Expressions The regular expression functions are used to perform various pattern matching activities: preg_match), preg_match_all) - match and extract) a pattern or all patterns from a string. preg_replace) - replace substrings that match a pattern with another substring. preg_split) - split a string based on a pattern. preg_grep) - find all elements of an array that match a pattern. Regular Expressions $x = 'abcdefghijk'; if preg_match'/def/', $x)) { print "Found the string."; } patterns are enclosed within delimiters - usually slashes /def/

7 Some characters have special meanings Matches Pattern True False. any single characters /c.t/ cat, execute coat ^ beginning of string /^cat/ cat, caterpiller application $ end of string /cat$/ cat, wildcat application or /cat dog/ application, dogged \b word boundary /\bcat/ cat, catalog, big cat wildcat \B non-word boundary /\Bcat/ wildcat cat, catalog Matches Pattern True False \s whitespace /c\st/ mac technology cat \S non-whitespace /c\st/ application mac tech \w word character 0-9,az,A-Z,_) /c\wt/ cat, application c$t \W non-word character /c\wt/ c$t cat \d digit /\d\d\d/ 123, abc123def a1b2c3 \D non-digit /\D\D\D/ some text 123ab456 modifiers A backslash can be used to "escape" any reserved characters /c.t/ - matches c.t and also cat, cot, cut /c\.t/ - matches c.t and nothing else Custom character patterns can be constructed using square brackets /c[aou]t/ - matches cat, cot, or cut, but not cet or cit a hyphen can be used to specify a range /c[a-fu-z]t/ - matches cat, cbt, cct, or cut, cvt, czt but not cit or cot /[0-9a-fA-F]/ - matches a hexadecimal character

8 a caret after the [ indicates negation /c[^aou]t/ - matches cet, cit, but not cat, cot, or cut /c[aou^ei]t/ - can't mix - caret must be at the beginning - if not, it's treated like a caret quantity modifiers Pattern Quantity Modifiers Matches Pattern True False * 0 or more times /ca*t/ ct, cat, caaaat cabat + 1 or more times /ca+t/ cat, caaaat ct? 0 or 1 times /ca?t/ ct, cat caaaat {n} Exactly n times /ca{3}t/ caaat {n,m} Between n and m times inclusively) ct, cat, caaaat /ca{1,3}t/ cat, caat, caaat ct, caaaat {n,} At least n times /ca{2,}t/ caat, caaaaat ct, cat parens Parenthesis have 2 purposes: Grouping Remembering Parenthesis for grouping or /\d?\d?\d?-?\d\d\d-\d\d\d\d/ /\d{3}?-?\d\d\d-\d\d\d\d/ /\d\d\d-)?\d\d\d-\d\d\d\d/ /\d{3}-)?\d{3}-\d{4}/

9 Parenthesis for remembering $phone = "The phone number is "; preg_match'/\d{3}-)?\d{3})-\d{4})/', $phone, $parts); print_r$parts); [0] => [1] => [2] => 555 [3] => 1212 ) $phone = "The phone number is "; preg_match'/\d{3}-)?\d{3})-\d{4})/', $phone, $parts); print_r$parts); [0] => [1] => 513- [2] => 555 [3] => 1212 ) /\d{3})?-?\d{3})-\d{4})/ - allows for or /\d{3})-)?\d{3})-\d{4})/ [0] => [1] => 513- [2] => 513 [3] => 555 [4] => 1212 ) A?: following an open paren causes the paren to be used for grouping but not remembering /?:\d{3})-)?\d{3})-\d{4})/ [0] => [1] => 513 [2] => 555 [3] => 1212 )

10 Rememberd patterns can also be referenced using \1, \2, \3, etc. /.).)\2\1/ Would match - abba, toot, otto, dood Would not match - abab abaa, abbb trailing options Trailing options Various modifiers can be added after the trailing slash i - ignore case /[0-9a-fA-F]/ - hexadecimal character /[0-9a-f]/i - same functions Regular Expression Functions Below are the function used with regular expressions: preg_match), preg_match_all) - match and extract) a pattern or all patterns from a string. preg_replace) - replace substrings that match a pattern with another substring. preg_split) - split a string based on a pattern. preg_grep) - find all elements of an array that match a pattern. preg_match preg_match preg_match) is used to match a single pattern in a string Stands for Perl-style Regular Expression Matching preg_matchpattern, string [, matches]) Returns 1 if the pattern matched, 0 if not. preg_match example

11 preg_match $ssn = ' '; if preg_match'/\d{3})-\d{2})-\d{4})/', $ssn, $parts)) { print_r$parts); } else { print "SSN not valid."; } [0] => [1] => 123 [2] => 45 [3] => 6789 ) preg_match_all preg_match_all preg_match_all) is used to match all occurrences of a pattern in a string preg_match_allpattern, string, matches [,order]) Returns the number of matches preg_match_all example preg_match_all $ssn = ' and '; preg_match_all'/\d{3})-\d{2})-\d{4})/', $ssn, $matches); print_r$matches); [0] => [0] => [1] => [1] => [0] => 123 [1] => 987 [2] => [0] => 45 [1] => 65 [3] => [0] => 6789 [1] => 4321 PREG_SET_ORDER preg_match_all $ssn = ' and '; preg_match_all'/\d{3})-\d{2})-\d{4})/', $ssn, $matches, PREG_SET_ORDER); print_r$matches); [0] => [0] => [1] => 123 [2] => 45 [3] => 6789 [1] => [0] => [1] => 987 [2] => 65 [3] => 4321 preg_replace

12 preg_replace preg_replace) is used replace strings based on a pattern preg_replacepattern, replacement, string [,limit]) Returns the replaced string preg_replace example preg_replace $html = 'Do <b>not</b> press the button.'; $text = preg_replace'/<[^>]+>/', '!', $html); print $text; Do!not! press the button. backreferences preg_replace $1, $2, etc. hold references to "remembered" items $names = 'Kent Covert, Tim Kingman, John Moose, Dirk Tepe'; $rnames = preg_replace'/\w+)\s\w+),/', "$2 $1,", $names); print $rnames; Covert Kent, Kingman Tim, Moose John, Tepe Dirk execute modifier preg_replace adding the e modifier after the pattern will cause the replacement string to be treated as PHP code with the result used as the replacement $headline = 'this is the big story'; $new = preg_replace'/\b\w)/e', "strtoupper$1)", $headline); print $new; This Is The Big Story arrays

13 preg_replace any or all of the first 3 arguments can be an array preg_replacepattern, replacement, string [,limit]) preg_split preg_split preg_split) is used split strings based on a pattern preg_splitpattern, string [,limit [,flags]]) Returns an array of the split items preg_split example preg_split $html = 'Do <b>not</b> press the <u>button</u>.'; $items = preg_split'/<[^>]+>/', $html); print_r$items); [0] => Do [1] => not [2] => press the [3] => button [4] =>. ) preg_split $html = 'Do <b>not</b> press the <u>button</u>.'; $items = preg_split'/\s*<[^>]+>\s*/', $html); print_r$items); [0] => Do [1] => not [2] => press the [3] => button [4] =>. ) preg_split flags

14 preg_split 2 flags can be used to modify the results of preg_split) PREG_SPLIT_NO_EMPTY - Doesn't return empty "chunks" PREG_SPLIT_DELIM_CAPTURE - returns separators as well as the separated items preg_grep preg_grep preg_grep) is used return elements from an array that match a pattern preg_greppattern, array) Returns an array of the matched items $textfiles = preg_grep'/\.txt$/', $filenames); preg_split example Questions? Homework #6