MCIS/UA PHP Training 2003 Chapter 6 Strings String Literals - - PowerPoint PPT Presentation

mcis ua
SMART_READER_LITE
LIVE PREVIEW

MCIS/UA PHP Training 2003 Chapter 6 Strings String Literals - - PowerPoint PPT Presentation

MCIS/UA PHP Training 2003 Chapter 6 Strings String Literals Single-quoted strings Double-quoted strings escape sequences String Literals Interpreted items Single-quoted Double-quoted \' - single quote variables - value of


slide-1
SLIDE 1

PHP Training 2003 Chapter 6 Strings

MCIS/UA

slide-2
SLIDE 2

String Literals

  • Single-quoted strings
  • Double-quoted strings

escape sequences

slide-3
SLIDE 3

String Literals

heredoc

Single-quoted Double-quoted \' \\

  • single quote
  • backslash

variables \n \r \t \\ \$ \" \nnn \xnn

  • value of variable
  • new line
  • return
  • tab
  • backslash
  • dollar sign
  • double quote
  • ASCII char in octal
  • ASCII char in hex

Interpreted items

slide-4
SLIDE 4

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.

slide-5
SLIDE 5

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

slide-6
SLIDE 6

Here Documents

$name = $info->queryFirstColumn(<<< end_of_sql SELECT name FROM info WHERE uniqueid = ? end_of_sql , $uid);

  • utputting
slide-7
SLIDE 7

Outputting strings

  • Several ways to output strings and other data:

echo print printf sprintf print_r var_dump

echo and print

slide-8
SLIDE 8

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

slide-9
SLIDE 9

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

slide-10
SLIDE 10

printf

modifiers

format result input

  • utput

%% %d %f %s %b %c %o %x %X %u percent sign integer floating point string binary character

  • ctal

hex (lowercase) hex (uppercase) unsigned integer

  • 123.45
  • 123.45

abc 5 65 255 123456789 123456789

  • 123.45

%

  • 123
  • 123.450000

abc 101 A 377 75bcd15 75BCD15 4294967173

Format Codes

slide-11
SLIDE 11

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
  • utput; for floats - number of digits before the

decimal point

  • .number - for floats, the number of decimal digits

modifier examples

slide-12
SLIDE 12

printf

printf("%5d", 3); ____3 printf("%-5d", 3); 3____ printf("%05d", 3); 00003 printf("%8f", 3.5); _______3.500000 printf("%8.3f", 3.5); _______3.500 printf("%08.3f", 3.5); 00000003.500

slide-13
SLIDE 13

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

slide-14
SLIDE 14

sprintf

  • sprintf formatted data and returns a string

$x = sprintf("%05d", 3); print $x; 00003

print_r

slide-15
SLIDE 15

print_r

  • print_r can be used to dump variables

$x = array(1, "abc", array("covertka" => "Kent", "kingmatm" => "Tim")); print_r($x); Array ( [0] => 1 [1] => abc [2] => Array ( [covertka] => Kent [kingmatm] => Tim ) )

var_dump

slide-16
SLIDE 16

var_dump

  • var_dump can also be used to dump variables

$x = array(1, "abc", array("covertka" => "Kent", "kingmatm" => "Tim")); var_dump($x); array(3) { [0]=> int(1) [1]=> string(3) "abc" [2]=> array(2) { ["covertka"]=> string(4) "Kent" ["kingmatm"]=> string(3) "Tim" } }

string functions

slide-17
SLIDE 17

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

slide-18
SLIDE 18

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

slide-19
SLIDE 19

Useful string functions

str_repeat() - used to repeat a string a number

  • f 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.)

slide-20
SLIDE 20

Useful string functions

htmlentities(), htmlspecialchars() - encodes html special characters (< > & ' ", etc.) rawurlencode(), rawurldecode(), urlencode(), urldecode() - encodes a URL

regular expressions

slide-21
SLIDE 21

Regular Expressions

555-1212 preg_match('/\d\d\d-\d\d\d\d/', $phone); 513-555-1212 preg_match('/(\d\d\d-)?\d\d\d-\d\d\d\d/', $phone); (513)555-1212 or (513) 555-1212 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);

slide-22
SLIDE 22

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.

slide-23
SLIDE 23

Regular Expressions

$x = 'abcdefghijk'; if (preg_match('/def/', $x)) { print "Found the string."; }

patterns

slide-24
SLIDE 24

Patterns

  • Patterns are enclosed within delimiters -

usually slashes /def/

slide-25
SLIDE 25

Patterns

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

  • r

/cat|dog/ application, dogged \b word boundary /\bcat/ cat, catalog, big cat wildcat \B non-word boundary /\Bcat/ wildcat cat, catalog

slide-26
SLIDE 26

Patterns

modifiers

Matches Pattern True False \s whitespace /c\st/ mac technology cat \S non-whitespace /c\St/ application mac tech \w word character (0-9,a- z,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

slide-27
SLIDE 27

Patterns

  • 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

slide-28
SLIDE 28

Patterns

  • 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

slide-29
SLIDE 29

Patterns

  • 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

slide-30
SLIDE 30

Pattern Quantity Modifiers

parens

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 ct, cat, caaaat {n,m} Between n and m times (inclusively) /ca{1,3}t/ cat, caat, caaat ct, caaaat {n,} At least n times /ca{2,}t/ caat, caaaaat ct, cat

slide-31
SLIDE 31

Patterns

  • Parenthesis have 2 purposes:
  • Grouping
  • Remembering

slide-32
SLIDE 32

Patterns

  • Parenthesis for grouping

555-1212 or 513-555-1212

/\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}/

slide-33
SLIDE 33

Patterns

  • Parenthesis for remembering

$phone = "The phone number is 555-1212."; preg_match('/(\d{3}-)?(\d{3})-(\d{4})/', $phone, $parts); print_r($parts);

Array ( [0] => 555-1212 [1] => [2] => 555 [3] => 1212 )

slide-34
SLIDE 34

Patterns

$phone = "The phone number is 513-555-1212."; preg_match('/(\d{3}-)?(\d{3})-(\d{4})/', $phone, $parts); print_r($parts); Array ( [0] => 513-555-1212 [1] => 513- [2] => 555 [3] => 1212 )

slide-35
SLIDE 35

Patterns

/(\d{3})?-?(\d{3})-(\d{4})/

  • allows for -555-1212 or 513555-1212

/((\d{3})-)?(\d{3})-(\d{4})/ Array ( [0] => 513-555-1212 [1] => 513- [2] => 513 [3] => 555 [4] => 1212 )

slide-36
SLIDE 36

Patterns

  • A ?: following an open paren causes the paren to

be used for grouping but not remembering

/(?:(\d{3})-)?(\d{3})-(\d{4})/ Array ( [0] => 513-555-1212 [1] => 513 [2] => 555 [3] => 1212 )

slide-37
SLIDE 37

Patterns

  • 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

slide-38
SLIDE 38

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

slide-39
SLIDE 39

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

slide-40
SLIDE 40

preg_match

  • preg_match() is used to match a single pattern

in a string

  • Stands for Perl-style Regular Expression

Matching preg_match(pattern, string [, matches])

  • Returns 1 if the pattern matched, 0 if not.

preg_match example

slide-41
SLIDE 41

preg_match

$ssn = '123-45-6789'; if (preg_match('/(\d{3})-(\d{2})-(\d{4})/', $ssn, $parts)) { print_r($parts); } else { print "SSN not valid."; }

Array ( [0] => 123-45-6789 [1] => 123 [2] => 45 [3] => 6789 )

preg_match_all

slide-42
SLIDE 42

preg_match_all

  • preg_match_all() is used to match all
  • ccurrences of a pattern in a string

preg_match_all(pattern, string, matches [,order])

  • Returns the number of matches

preg_match_all example

slide-43
SLIDE 43

preg_match_all

$ssn = '123-45-6789 and 987-65-4321'; preg_match_all('/(\d{3})-(\d{2})-(\d{4})/', $ssn, $matches); print_r($matches); Array [0] => Array [0] => 123-45-6789 [1] => 987-65-4321 [1] => Array [0] => 123 [1] => 987 [2] => Array [0] => 45 [1] => 65 [3] => Array [0] => 6789 [1] => 4321

PREG_SET_ORDER

slide-44
SLIDE 44

preg_match_all

$ssn = '123-45-6789 and 987-65-4321'; preg_match_all('/(\d{3})-(\d{2})-(\d{4})/', $ssn, $matches, PREG_SET_ORDER); print_r($matches);

Array [0] => Array [0] => 123-45-6789 [1] => 123 [2] => 45 [3] => 6789 [1] => Array [0] => 987-65-4321 [1] => 987 [2] => 65 [3] => 4321

preg_replace

slide-45
SLIDE 45

preg_replace

  • preg_replace() is used replace strings based on

a pattern preg_replace(pattern, replacement, string [,limit])

  • Returns the replaced string

preg_replace example

slide-46
SLIDE 46

preg_replace

$html = 'Do <b>not</b> press the button.'; $text = preg_replace('/<[^>]+>/', '!', $html); print $text;

Do !not! press the button.

backreferences

slide-47
SLIDE 47

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

slide-48
SLIDE 48

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

slide-49
SLIDE 49

preg_replace

  • any or all of the first 3 arguments can be an array

preg_replace(pattern, replacement, string [,limit])

preg_split

slide-50
SLIDE 50

preg_split

  • preg_split() is used split strings based on a

pattern preg_split(pattern, string [,limit [,flags]])

  • Returns an array of the split items

preg_split example

slide-51
SLIDE 51

preg_split

$html = 'Do <b>not</b> press the <u>button</u>.'; $items = preg_split('/<[^>]+>/', $html); print_r($items);

Array ( [0] => Do [1] => not [2] => press the [3] => button [4] => . )

slide-52
SLIDE 52

preg_split

$html = 'Do <b>not</b> press the <u>button</u>.'; $items = preg_split('/\s*<[^>]+>\s*/', $html); print_r($items);

Array ( [0] => Do [1] => not [2] => press the [3] => button [4] => . )

preg_split flags

slide-53
SLIDE 53

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

slide-54
SLIDE 54

preg_grep

  • preg_grep() is used return elements from an

array that match a pattern preg_grep(pattern, array)

  • Returns an array of the matched items

$textfiles = preg_grep('/\.txt$/', $filenames); preg_split example

slide-55
SLIDE 55

Questions?

slide-56
SLIDE 56

Homework #6