PHP Using Strings 1
Replacing substrings (replace certain parts of a document template; ex with client’s name etc) mixed str_replace (mixed $needle, mixed $new_needle, mixed $haystack[, int $count] ) Replaces all instances of $needle in $haystack with $new_needle Returns a new string = a copy of $haystack with all replacements made $count has to be a variable (lhs) that will be set to the number of replacements made $needle, $new_needle, $haystack can be strings or arrays Matching & replacing with string functions 2
Feeback.html s/feedback.html s/feedback.html s/processfeedback_v2_php.pdf s/processfeedback_v2_php.pdf 3
The match function is int preg_match(string $pattern, string $str [, array &$matches [, …]]) 1 st argument is the pattern 2 nd argument is the subject string Returns number of matches found: 1 (true) if there is a match – it stops at the first match found! 0 (false) otherwise An optional 3 rd argument will capture the actual matched string and the parenthesized subpatterns, if any. int preg_match_all(…) Use to find all matches to the regular expression 4 Regular Expressions
Character Classes [A-Z]uppercase letter [a-z]lowercase letter [0-9]digit {5}exactly five {3,}three or more {1,4}one to four 5
Metacharacters ^beginning of string $end of string 6
Regular Expression Username – 5 to 10 lowercase letters? $pattern = '/^[a-z]{5,10}$/'; if (!preg_match($pattern, $username)) { echo " $username is invalid. "; } 7
Regular Expressions Social Security Number $pattern = '/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/'; if (!preg_match($pattern, $ssn)) { echo " $ssn is invalid. "; } 8
Character classes \dany digit \Dany non-digit \wAny letter, number, or underscore \WAnything that is not a letter, number, or underscore \swhitespace (space, tab, new line, etc.) \SAn y non-whitespace 9
Regular Expressions Social Security Number $pattern = '/^\d{3}-\d{2}-\d{4}$/'; if (!preg_match($pattern, $ssn)) { echo " $ssn is invalid. "; } 10
Metacharacters [0-9]** = zero or more [A-Z]++ = one or more.. = match any character ([A-Z]\. )?? = either zero or one 11
Regular Expressions Last name: Frank $pattern = '/^[A-Z][a-z]+$/'; if (!preg_match($pattern, $last)) { echo " $last is invalid. "; } 12
Regular Expressions Name: Charles Frank or Charles E. Frank $pattern = '/^[A-Z][a-z]+ ([A-Z]\. )?[A-Z][a-z]+ $/'; if (!preg_match($pattern, $name)) { echo " $name is invalid. "; } 13