PHP with Regular Expressions Web Technologies Computing Science Thompson Rivers University.

Slides:



Advertisements
Similar presentations
Session 3BBK P1 ModuleApril 2010 : [#] Regular Expressions.
Advertisements

BBK P1 Module2010/11 : [‹#›] Regular Expressions.
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Form Validation CS What is form validation?  validation: ensuring that form's values are correct  some types of validation:  preventing blank.
Chapter 14 Perl-Compatible Regular Expressions Part 1.
Data Manipulation & Regular Expressions CSCI 215.
1 Query Languages. 2 Boolean Queries Keywords combined with Boolean operators: –OR: (e 1 OR e 2 ) –AND: (e 1 AND e 2 ) –BUT: (e 1 BUT e 2 ) Satisfy e.
Computer & Network Forensics
Using regular expressions Search for a single occurrence of a specific string. Search for all occurrences of a string. Approximate string matching.
Tutorial 14 Working with Forms and Regular Expressions.
Form Validation CS What is form validation?  validation: ensuring that form's values are correct  some types of validation:  preventing blank.
CS 174: Web Programming February 26 Class Meeting Department of Computer Science San Jose State University Spring 2015 Instructor: Ron Mak
More on Regular Expressions Regular Expressions More character classes \s matches any whitespace character (space, tab, newline etc) \w matches.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Regular Expressions in ColdFusion Applications Dave Fauth DOMAIN technologies Knowledge Engineering : Systems Integration : Web.
REGULAR EXPRESSIONS CHAPTER 14. REGULAR EXPRESSIONS A coded pattern used to search for matching patterns in text strings Commonly used for data validation.
XP Tutorial 14 New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Last Updated March 2006 Slide 1 Regular Expressions.
Regular Expressions Week 07 TCNJ Web 2 Jean Chu. Regular Expressions Regular Expressions are a powerful way to validate and format text strings that may.
Tutorial 14 Working with Forms and Regular Expressions.
 Text Manipulation and Data Collection. General Programming Practice Find a string within a text Find a string ‘man’ from a ‘A successful man’
Faculty of Sciences and Social Sciences HOPE JavaScript Validation Regular Expression Stewart Blakeway FML
PHP Workshop ‹#› Data Manipulation & Regex. PHP Workshop ‹#› What..? Often in PHP we have to get data from files, or maybe through forms from a user.
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
PHP Using Strings 1. Replacing substrings (replace certain parts of a document template; ex with client’s name etc) mixed str_replace (mixed $needle,
CIS 451: Regular Expressions Dr. Ralph D. Westfall January, 2009.
Finding the needle(s) in the textual haystack
Regular Expressions Regular expressions are a language for string patterns. RegEx is integral to many programming languages:  Perl  Python  Javascript.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Perl and Regular Expressions Regular Expressions are available as part of the programming languages Java, JScript, Visual Basic and VBScript, JavaScript,
CS 174: Web Programming September 30 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
1 CSC 594 Topics in AI – Text Mining and Analytics Fall 2015/16 4. Document Search and Regular Expressions.
Regular Expressions.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2015, Fred McClurg, All Rights.
Regular Expressions in PHP. Supported RE’s The most important set of regex functions start with preg. These functions are a PHP wrapper around the PCRE.
Overview A regular expression defines a search pattern for strings. Regular expressions can be used to search, edit and manipulate text. The pattern defined.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2010 All Rights Reserved. 1.
Regular Expressions for PHP Adding magic to your programming. Geoffrey Dunn
1 PHP Intro PHP Strings After this lecture, you should be able to: Manipulate and Output PHP Strings: Manipulate and Output PHP Strings: Single- or Double-quoted.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
12. Regular Expressions. 2 Motto: I don't play accurately-any one can play accurately- but I play with wonderful expression. As far as the piano is concerned,
CS346 Regular Expressions1 Pattern Matching Regular Expression.
GREP. Whats Grep? Grep is a popular unix program that supports a special programming language for doing regular expressions The grammar in use for software.
PHP’s Regular Expression Functions (Perl Compatible) Examples taken from: Beginning PHP 5 and MySQL 5 From Novice to Professional.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
CSC 2720 Building Web Applications PHP PERL-Compatible Regular Expressions.
Perl Day 4. Fuzzy Matches We know about eq and ne, but they only match things exactly We know about eq and ne, but they only match things exactly –Sometimes.
CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Regular Expressions.
Validation using Regular Expressions. Regular Expression Instead of asking if user input has some particular value, sometimes you want to know if it follows.
Unit 11 –Reglar Expressions Instructor: Brent Presley.
7 Copyright © 2009, Oracle. All rights reserved. Regular Expression Support.
XP Tutorial 7 New Perspectives on JavaScript, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
An Introduction to Regular Expressions Specifying a Pattern that a String must meet.
Regular expressions Day 11 LING Computational Linguistics Harry Howard Tulane University.
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.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
Lesson 4 String Manipulation. Lesson 4 In many applications you will need to do some kind of manipulation or parsing of strings, whether you are Attempting.
Regular Expressions.
Regular Expressions Upsorn Praphamontripong CS 1110
Regular Expressions 'RegEx'.
Perl-Compatible Regular Expressions Part 1
Regular Expressions in Perl
Pattern Matching in Strings
Working with Forms and Regular Expressions
WEB PROGRAMMING JavaScript.
Functions, Regular expressions and Events
Data Manipulation & Regex
CIT 383: Administrative Scripting
Presentation transcript:

PHP with Regular Expressions Web Technologies Computing Science Thompson Rivers University

Regular Expressions2 1. How to Use Regular Expressions [Q] When a user registers in our application or changes his/her password, how can the application enforce him/her to use a good password? [Q] Good password? Minimum 8 charters At least one special character or number [Q] How to verify the format? [Q] How to find … in a b web document? Link, title, comment, tags No title [Q] Can we read the title from google.com?

Regular Expressions3 [Q] What is a regular expression? They are coded patterns that you can use to search for matching patterns in text strings. They are commonly used to validate the data that users enter in web forms. [Q] Examples? 1. How to create and use regular expressions How to create and use regular expressions 2. How to match characters How to match characters 3. How to use the character class How to use the character class 4. How to create complex patterns How to create complex patterns 5. How to use look-ahead assertions How to use look-ahead assertions 6. How to use a multiline regular expression How to use a multiline regular expression 7. How to replace a regular expression with a string How to replace a regular expression with a string 8. How to split a string on a regular expression How to split a string on a regular expression 9. Regular expressions for data validation Regular expressions for data validation

Regular Expressions4 How to create and use regular expressions preg_match($pattern, $str)It returns 1 if the pattern is found and 0 if it’s not found. If there is an error in the pattern, it returns FALSE. $pattern = '/Harris/'; // case sensitive? $author_match = preg_match($pattern, 'Ray Harris'); // ? $editor_match = preg_match($pattern, 'Joel Murach'); // ? $pattern = '/murach/i'; // case insensitive? $editor_match = preg_match($pattern, 'Joel Murach'); // ? 1.

Regular Expressions5 How to match characters \\ \/ \t \n \r \f \xhhThe hexadecimal for a character $string = "  2010 Mike's Music. \ All rights reserved (5/2010)."; preg_match('/\xA9/', $string); // ? preg_match('///', $string); // something wrong? FALSE? preg_match('/\//', $string); // ? preg_match('/\\\\/', $string); // ? // Be careful with '\' // '\\' or "\\" is interpreted as a single backslash.

Regular Expressions6 How to match types of characters.Any single chracter except a new line \wAny letter, number, or the underscore \WAny character that is not a letter, number or the underscore \dAny digit \DAny character that is not a digit \sAny whitespace chracter (space, tab, new line, carrige return, form feed, or vertical tab) \SAny character that is not whitespace $string = 'The product code is MBT-3461'; preg_match('/MB./', $string); // ? preg_match('/MB\d/', $string); // ? preg_match('/MB-\d/', $string); // ? 1.

Regular Expressions7 How to use the character class [chars]a single character that is listed inside the brackets $string = 'The product code is MBT-3461'; preg_match('/MB[TF]/', $string); // ? preg_match('/[.]/', $string); // ? preg_match('/MB[TF]/', $string); // ? preg_match('/[12345]/', $string); // ? ^[^aeiou]Negates the list of characters -[a-z]Creates a range of characters preg_match('/MB[^TF]/', $string); // ? preg_match('/MBT[^^]/', $string); // ? preg_match('/MBT-[1-5]/', $string); // ? preg_match('/MBT[_*-]/', $string); // ?

Regular Expressions8 [:digit:]Digits (same as \d ?) [:lower:]Lower case letters [:upper:]Upper case letters [:letter:]Upper and lower case letters [:alnum:]Upper and lower case letters and digits [:word:]Upper and lower case letters, digits, and the underscore (same as \w ?) [:print:]All printable characters including the space [:graph:]All printable characters excluding the space [:punct:]All printable characters excluding letters and digits, i.e., special characters? $string = "The product code is MBT-3461"; preg_match('/MBT[[:punct:]]/', $string); // ? preg_match('/MBT[[:digit:]]/', $string); // ? preg_match('/MB[[:upper:]]/', $string); // ? 1.

Regular Expressions9 How to create complex patterns ^The begining of the string $The end of the string \bThe beginning or end of a word \BA position other than the beginning or end of a word $author = 'Ray Harris'; preg_match('/^Ray/', $author); // ? preg_match('/Harris$/', $author); // ? preg_match('/^Harris/', $author); // ??? $editor = 'Anne Bohme'; preg_match('/Ann/', $editor); // ? preg_match('/Boh\b/', $editor); // ??? ***

Regular Expressions10 (subspattern)Creates a numbered subpattern group (?:subpattern)Creates an unnumbered subpattern group |Matches either the left or the right subpattern \nMatches a numbered subpattern group $name = 'Rob Robertson'; preg_match('/^(Rob)\b/', $name); // ? preg_match('/^(Rob)|(Bob)\b/', $name); // ? preg_match('/^(\w\w\w) \1/', $name); // \1 stands for the three exact characters // that are matched with \w\w\w ? // [Q] The above regular expression searchs for \w\w\w // or \w\w\w \w\w\w ???

Regular Expressions11 {n}Pattern must repeat exactly n times {n,}Pattern must repeat n or more times {n,m}Subpattern must repeat from n to m times ?Zero or one of the previous subpattern +One or more of the previous subpattern *Zero or more of the previous subpattern $phone = ' '; // pattern for phone numbers? preg_match('/^\d{3}-\d{3}-\d{4}$/', $phone); // ? $fax = '(559) '; preg_match('/^\(\d{3}\) *\d{3}-\d{4}$/', $fax); // ? // pattern for for both ? $phone_pattern = '/^(\d{3}-)|(\(\d{3}\) +)\d{3}-\d{4}$/'; preg_match($phone_pattern, $phone); // ? preg_match($phone_pattern, $fax); // ? 1.

Regular Expressions12 How to use look-ahead assertions [Q] How to enforce users to include a special character in passwords? An assertion is a fact about the pattern that must be true. (?=assertion)Creates a look-ahead assertion (?!assertion)Creates a negative look-ahead assertion (?=[[:digit:]])The next character in the pattern must be digit (?=.*[[:digit:]])The pattern must contain at least one digit $pattern = '/^(?=.*[[:digit:]])[[:alnum:]]{6}$/'; preg_match($pattern, 'Harris'); // ? preg_match($pattern, 'Harri5'); // ? preg_match($pattern, 'Harrison5'); // ?

Regular Expressions13 $pattern = '/^(?!3[2-9])[0-3][[:digit:]]$/'; // good to use to check months preg_match($pattern, '32'); // ? preg_match($pattern, '31'); // ? preg_match($pattern, '21'); // ? $pw_pattern = // [Q] password pattern? // Should include a digit, a special // character and minimum 8 characters. '/^(?=.*[[:digit:]])(?=.*[[:punct:]])[[:print:]]{8,}$/'; preg_match($pw_pattern, 'sup3rsecret'); // ? preg_match($pw_pattern, 'sup3rse(ret'); // ? preg_match($pw_pattern, 'su3)rt'); // ? 1.

Regular Expressions14 How to use a multiline regular expression $string = "Ray Harris\nAuthor"; $pattern1 = '/Harris$/'; preg_match($pattern1, $string); // no? $pattern2 = '/Harris$/m'; // multiline preg_match($pattern2, $string); // ?

Regular Expressions15 A function to find/get multiple matches in a string preg_match_all($pattern, $string, $matches) Returns a count of the number of matches or FALSE. Also stores all matched substrings as a multi- dimensional array in the $matches. $matches[0] is an array of full pattern matches. If the pattern contains numbered parenthesized subpatterns, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. preg_match($pattern, $string, $matches) // the 1 st match $string = 'MBT-6745 MBT-5712'; $pattern = '/MBT-[[:digit:]]{4}/'; $count = preg_match_all($pattern, $string, $matches); // ? foreach($matches[0] as $match) echo ' '. $match. ' '; // ? 1.

Regular Expressions16 How to replace a regular expression with a string How to split a string on a regular expression preg_replace($pattern, $new, $string) preg_split($pattern, $string)Returns an array of strings that's created by splitting the string on the specified pattern. $items = 'MBT-6745 MBS-5729'; $items = preg_replace('/MB[TS]/', 'ITEM', $items); $items = 'MBT-6745 MBS-5729, MBT-6824, and MBS-5214'; $pattern = '/[, ]+(and[ ]*)?/'; // ? $items = preg_split($pattern, $items); foreach($items as $item) echo ' '. $item. ' '; // ? 1.

Regular Expressions17 Regular expressions for data validation [Q] Phone numbers: '/^[[:digit:]{3}-[[:digit:]{3}-[[:digit:]{4}$/' [Q] Credit card numbers: '/^[[:digit:]{4}-[[:digit:]{4}-[[:digit:]{4}-[[:digit:]{4}$/' [Q] Zip code: or '/^[[:digit:]{5}(-[[:digit:]{4})?$/' [Q] Dates: mm/dd/yyyy '/^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][[:digit:]]|3[01])\/[[:digit:]]{4}$/' [Q] address ?

Regular Expressions18 [Q] address ? function valid_ ($ ) { $parts = $ ); if (count($parts) != 2 ) return false; if (strlen($parts[0]) > 64) return false; if (strlen($parts[1]) > 255) return false; $atom = '[[:alnum:]_!#$%&\'*+\/=?^`{|}~-]+'; $dotatom = '(\.'. $atom. ')*'; $address = '(^'. $atom. $dotatom. '$)'; $char = '([^\\\\"])'; $esc = '(\\\\[\\\\"])'; $text = '('. $char. '|'. $esc. ')+'; $quoted = '(^"'. $text. '"$)'; $local_part = '/'. $address. '|'. $quoted. '/'; $local_match = preg_match($local_part, $parts[0]); if ($local_match === false || $local_match != 1) return false; $hostname = '([[:alnum:]]([-[:alnum:]]{0,62}[[:alnum:]])?)'; $hostnames = '('. $hostname. '(\.'. $hostname. ')*)'; $top = '\.[[:alnum:]]{2,6}'; $domain_part = '/^'. $hostnames. $top. '$/'; $domain_match = preg_match($domain_part, $parts[1]); if ($domain_match === false || $domain_match != 1) return false; return true; }

Regular Expressions19 [Q] How to get … in an URL? function getTitle($url) { $str = file_get_contents($url); // should be if (strlen($str) > 0) { // for non-greedy matching, // meaning stop after the first match, // not preg_match_all() preg_match("/\ (.*)\ /", $str, $title); return $title[1]; // not...[0]; for the first captured // parenthesized subpattern } else return ''; } 1.