variable variables a variable variable has as its value the name of another variable without $...

22
Variable Variables A variable variable has as its value the name of another variable without $ prefix E.g., if we have $addr, might have a statement $tmp = 'addr'; Can now use the name of the variable variable prefixed by an additional $ in place of variable whose name (w/o $) was assigned to it E.g., , $$tmp = "10 Elm Row"; assigns “10 Elm Row” to $addr echo 'Go to '.$$tmp; outputs Go to followed by value of $addr

Upload: christina-singleton

Post on 19-Jan-2018

289 views

Category:

Documents


0 download

DESCRIPTION

Example Have a form with text boxes with the 3 components of an address: street, city, and state. Values of name attributes are addr1, addr2, and add3 In script handling the request, PHP code before HTML tags  sets constant NUMADDRS to 3  copies values of form variables into $addr1, $addr2, and $addr3 PHP code in the body has a for loop ranging $i from 1 to 3  Loop body sets $tmp to "addr$i", i.e., name of variable $addr1, addr2, or $addr3 without $ prefix, depending on $i  Then outputs a string ending with $$tmp, i.e., value of $addr1, $addr2, or $addr3 (depending on $i )

TRANSCRIPT

Page 1: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Variable Variables A variable variable has as its value the name of another variable

without $ prefix

E.g., if we have $addr, might have a statement$tmp = 'addr';

Can now use the name of the variable variable prefixed by an additional $ in place of variable whose name (w/o $) was assigned to it

E.g., ,$$tmp = "10 Elm Row";

assigns “10 Elm Row” to $addrecho 'Go to '.$$tmp;

outputs Go to followed by value of $addr

Page 2: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Can’t replace concatenated string

'Go to'.$$tmpwith

"Go to $$tmp" The $$tmp inside double quotes is seen as a $ followed

by $tmp Value of $tmp is "addr"

Page 3: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Example Have a form with text boxes with the 3 components of an address:

street, city, and state. Values of name attributes are addr1, addr2, and add3 In script handling the request, PHP code before HTML tags

sets constant NUMADDRS to 3 copies values of form variables into $addr1, $addr2, and

$addr3 PHP code in the body has a for loop ranging $i from 1 to 3

Loop body sets $tmp to "addr$i", i.e., name of variable $addr1, addr2, or $addr3 without $

prefix, depending on $i Then outputs a string ending with $$tmp,

i.e., value of $addr1, $addr2, or $addr3 (depending on $i)

Page 4: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

<?php define( "NUMADDRS", 3 ); $addr1 = $_POST['addr1']; $addr2 = $_POST['addr2']; $addr3 = $_POST['addr3'];?><html><head> <title>Address</title></head><body> <p> Your address is

Continued

Page 5: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

<?php for ( $i=1; $i <= NUMADDRS; $i ++ ) { $tmp = "addr$i"; echo "<br>\n\t".$$tmp; } ?>

</p></body></html>

Page 6: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Use position specifiers to explicitly state which argument values go with which conversions specifiers To specify the n th argument after the format argument goes in this

position, put n$ just after % Use single quotes (else, e.g., "%1$d" appears to include a variable to

be interpolated)

Exampleprintf('The age of %2$s is %1$d.', 30, "John");

outputs The age of John is 30.

More on printf() (and sprintf())

Page 7: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

This allows an argument to be used more than once in the string—e.g., printf('%1$s is %3$d, %2$s is %6$d, %4$s is %6$d, %5$s is %3$d', "Ed", "Al", 39, "Pat", "Sue", 43); outputs Ed is 39, Al is 43, Pat is 43, Sue is 39

Page 8: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

sprintf() is just like prinft() but returns the formatted string instead of outputting it

Page 9: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Option Settings The (modifier) option can be changed from within the pattern by a

sequence of option letters (modifiers) enclosed between (? and )

The new option is in effect from that point to the end of the pattern or enclosing subpattern

E.g., "/ab(?is)c.d/" match "abc\nd" as well as "abC\nd"

Turn off an option by having it to the right of "-"—e.g., "/ab(?is)c.d(?-i)ef/"

Additional on PHP Regular Expressions

Page 10: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

If any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the ? and the : E.g., the following have the same effect

(?i:saturday|sunday)(?:(?i)saturday|sunday)

Page 11: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

\b, as in JavaScript, matches a word boundary \B matches where there is no word boundary

E.g., "/\Band\B/" matches "hands" but not "one and two" \Z and \z, unlike $, match only the very end of the subject string

even when the m modifier is used \Z matches before a newline that is the last character of the

string as well as at the end of the string \z matches only at the end

Simple (Point-based) Assertions

Page 12: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

\A, unlike ^, matches only the very start of the subject string even when the m modifier is used

If preg_match() is given a 4th argument, it’s the offset into the subject string where the search for a match starts E.g.,

preg_match("/ab/", "ababab", $m, 2) matches the 2nd "ab" in the "ababab"

\G is true only when the current matching position is at the start point of the match, as specified by the offset argument Differs from \A when the offset is non-zero E.g., preg_match("/\Gab/", "ababab", $m, 1) fails

Page 13: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Besides, e.g., \1, can also use \g1 or \g{1} The longer forms avoid ambiguity in some cases

\g with a negative number is a relative reference E.g., "/(foo)(bar)\g{-1}/" matches "foobarbar" and

"/(foo)(bar)\g{-2}/" matches "foobarfoo"

More on Back References

Page 14: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Can name a subpattern using the syntax (?P<name>pattern) Alternatively, (?<name>pattern) or (?'name'pattern) The subpattern is then indexed in the matches array by its

normal numeric position and also by name For backreference, can use (?P=name), \k<name>, \k'name', \

k{name}, or \g{name} Example

$pat = "/[a-z]+(?<num>\d+)[a-z]+/";$str = "abcd123efg";preg_match($pat, $str, $m);echo $m['num'] . " " . $m[1];

outputs 123 123

Named Subpatterns

Page 15: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Sometimes we need alternative capturing subpatterns Each gets its own backreference number even though only 1

ever matches The (?| syntax allows duplicate numbers E.g., matching

"/(?:(Sat)ur|(Sun))day/" against "Sunday", "Sun" is stored in backreference 2 and

backreference 1 is empty Using

"/(?|(Sat)ur|(Sun))day/" both "Sat" and "Sun" can get stored in backreference 1

Alternative Capturing Subpatterns

Page 16: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

An assertion subpattern is matched in the normal way but doesn’t change the current matching position

Lookaheads Lookaheads can be negative or positive A negative look ahead is denoted by ?!

Check that a given pattern isn’t following a match we’re making

Examples preg_match("/white(?!house)/", "His whitehouse");

Fails: the pattern says "white" shouldn’t be immediately followed by "house" preg_match("/white(?!house)/", "His white house");

Succeeds: cf. the space between "white" and "house"

Assertions

Page 17: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

A positive lookahead is denoted by ?= Check that a pattern follows a match we’re making E.g., "/pay(?=day)/"

Lookbehinds A positive lookbehind is denoted by ?<=

Check that a pattern precedes a match we’re making E.g., "/(?<=pay)day/"

A negative lookbehind is denoted by ?<! Check that a pattern doesn’t precede a match we’re making E.g., "/(?<!white)house/"

Page 18: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Can cause matching to obey a subpattern conditionally or to choose between two alternative subpatterns

The 2 forms are (?(condition)yes-pattern)(?(condition)yes-pattern|no-pattern) If the condition is satisfied, yes-pattern is used; else no-pattern

(if present) 2 kinds of condition If the text between the parentheses consists of a digit,

then the condition is satisfied if the capturing subpattern of that number has previously matched

Conditional Subpatterns

Page 19: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Example "/(\()\d+(?(1)\))/"

Matches a string of digits If the digits are preceded by a (, look for a closing )

If the condition isn’t a digit, it must be (2nd kind of condition) an assertion: positive or negative lookahead or lookbehind

Example "/((?=a)abc|zyx)/"

If the next character is an a, look for abc, else look for zyx

Page 20: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

Recall: preg_replace( pattern, replacement, subject ) returns string subject with all non-overlapping substrings matching regex pattern replaced by the string replacement

If subject is an array, then preg_replace() does the replacement on every element of the array and returns an array with the result (ordered as per the original)

Example$strs = array("2013-10-25", "2012-1-13");$strs1 = preg_replace("/(\d+)-(\d+)-(\d+)/", "$2/$3/$1", $strs);

foreach ( $strs1 as $s ) echo $s . " ";

outputs 10/25/2013 1/13/2012

preg_replace() with Array Arguments

Page 21: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

pattern and replacement can be arrays of the same length When an element of pattern matches, it’s replaced by the

corresponding element in replacement

Example Given

$pats = array("/([A-Z][a-z]*)\s+([A-Z][a-z]*)/", "/(\d+)-(\d+)-(\d+)/");$repls = array("$2, $1", "$2/$3/$1");

executing preg_replace($pats, $repls, "John Doe: 2012-1-13. Sue Smith: 2011-11-24");

returns Doe, John: 1/13/2012. Smith, Sue: 11/24/2011

Page 22: Variable Variables A variable variable has as its value the name of another variable without $ prefix…

The modifier e is specific to preg_replace() When pattern has an e modifier, preg_replace()

does normal substitution of backreferences in the replacement string,

evaluates the replacement string as PHP code, and uses the result for replacing the search string

Example—note that the replacement has to be double-quoted as it gets evaluated preg_replace("/ ([a-z])([a-z]*)/e", "' '.strtoupper('$1').'$2'", " john doe, mary smith")

returns the string " John Doe, Mary Smith"

Replacement Modifier e