Sys.Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 18: Regular Expressions in PHP.

Slides:



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

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
FORM VALIDATION Faheem Ahmed Khokhar. FORM VALIDATION Faheem Ahmed Khokhar.
BBK P1 Module2010/11 : [‹#›] Regular Expressions.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Scripting Languages Chapter 8 More About Regular Expressions.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Form Validation CS What is form validation?  validation: ensuring that form's values are correct  some types of validation:  preventing blank.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Applications of Regular Expressions BY— NIKHIL KUMAR KATTE 1.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
(c) Manzur Ashraf, Short course, KFUPM PHP & MySQL 1 Basic PHP Class 2.
Tutorial 14 Working with Forms and Regular Expressions.
Lecture 7: Perl pattern handling features. Pattern Matching Recall =~ is the pattern matching operator A first simple match example print “An methionine.
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
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
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 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Introduction To Perl Susan Lukose. Introduction to Perl Practical Extraction and Report Language Easy to learn and use.
CSE 311 Foundations of Computing I Lecture 17 Structural Induction: Regular Expressions, Regular Languages Autumn 2011 CSE 3111.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Programming in Perl regular expressions and m,s operators Peter Verhás January 2002.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2015, Fred McClurg, All Rights.
BY Sandeep Kumar Gampa.. What is Regular Expression? Regex in.NET Regex Language Elements Examples Regular Expression API How to Test regex in.NET Conclusion.
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.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 24 The String Section.
Instructor: Craig Duckett Lecture 08: Thursday, October 22 nd, 2015 Patterns, Order of Evaluation, Concatenation, Substrings, Trim, Position 1 BIT275:
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Regular Expressions Regular Expressions. Regular Expressions  Regular expressions are a powerful string manipulation tool  All modern languages have.
C# Strings 1 C# Regular Expressions CNS 3260 C#.NET Software Development.
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,
Introduction to Java Java Translation Program Structure
CS346 Regular Expressions1 Pattern Matching Regular Expression.
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.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
CSC 2720 Building Web Applications PHP PERL-Compatible Regular Expressions.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Random Bits of Perl None of this stuff is worthy of it’s own lecture, but it’s all a bunch of things you should learn to use Perl well.
CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Regular Expressions.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Compiler Construction By: Muhammad Nadeem Edited By: M. Bilal Qureshi.
Unit 11 –Reglar Expressions Instructor: Brent Presley.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
An Introduction to Regular Expressions Specifying a Pattern that a String must meet.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
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.
The Scripting Programming Language
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Arrays and Strings. Arrays in PHP Arrays are made up of multiple memory blocks, each with the same name and differentiated by an index number Each block.
Regular Expressions.
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Data Manipulation & Regex
PHP –Regular Expressions
Presentation transcript:

Sys.Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 18: Regular Expressions in PHP

Sys.Prog & Scripting - HW Univ2 PHP Control Structures if, while, do-while, for and foreach are all supported by PHP. <?php if($x > $y){ echo ‘x is greater than y’;} elseif($x < $y){ echo ‘x is less than y’;} else{ echo ‘x is equal to y’;} ?>

Sys.Prog & Scripting - HW Univ3 for/foreach for ($x = 1; $x <= 5; $x++) { echo $x; } Foreach is a convenient control structure to iterate through the items of an array. <?php $fruits = array (“apple” => “My favourite”, “banana” => “don’t like”, “pineapple” => “can eat”); foreach ($fruits as $key => $value) { echo "Key: $key; Value: $value \n"; } ?>

Sys.Prog & Scripting - HW Univ4 Regular Expressions As with most scripting languages, PHP has good support for regular expressions For the notation of basic regular expressions see Lecture 12 Here we discuss aspects specific to PHP Regular expressions are often used when iterating over the contents of a file, etc Regular expression are not only used to match strings, but also to replace

Sys.Prog & Scripting - HW Univ5 PHP & Regular Expressions PHP includes three sets of functions that support regular expressions. POSIX regular expressions: regex function set Extended regular expressions: (mb_)ereg function set Perl-style regular expressions: preg function set

Sys.Prog & Scripting - HW Univ6 The ereg Function Set Regular expressions are passed as strings. Supported in PHP 3, 4, 5. Part of core PHP. int ereg (string pattern, string subject [, array groups]) Checks if pattern matches subject. Returns the length of the match or zero if there is no match. If the 3 rd parameter is specified, the function will store the substrings matched in the elements of the array.

Sys.Prog & Scripting - HW Univ7 Examples ereg('[0-9]+', 'the number is 432'); Matches one or more digits ereg('pet.*(cat|dog)$', 'my pet is a cat'); Matches pet, followed by any sequence of characters, and cat or dog at the end ereg('pet.*(cat|dog)$', 'my pet is a cat', $matched); As above, storing the matched sub- expressions in the array matched Result: $matched = array ('my pet is a cat', 'cat')

Sys.Prog & Scripting - HW Univ8 The ereg Function Set (cont'd) string ereg_replace(string pattern, string replacement, string subject) Replace all matches of pattern with replacement. array split(string pattern, string subject [, int limit) Splits subject into an array of strings using the regular expression pattern Ref:

Sys.Prog & Scripting - HW Univ9 Examples ereg_replace('USER', 'hwloidl', 'insert the user name here: USER'); Replaces USER by hwloidl in the string split(',','one,two,three',$matched); Splits at each ',' in the string Result: $matched is array('one','two','three') $terms = split('[/+*-]', '3*5+i/6-12') Result: $term is array('3', '5', 'i', '6', '12')

Sys.Prog & Scripting - HW Univ10 The mb-ereg Function Set Very similar to the ereg function set with one difference: –ereg functions treat the regular expression and the subject strings as 8-bit characters. –mb_ereg supports multi-byte characters with various encodings. Ref:

Sys.Prog & Scripting - HW Univ11 The preg Function Set Regular expressions specified as a string using Perl syntax. Functions include: – preg_match – preg_match_all – preg_grep – preg_replace – preg_replace_callback Ref:

Sys.Prog & Scripting - HW Univ12 Perl Regular Expressions Patterns are delimited by / eg /pattern/ Additional character classes are provided: –\s whitespace; \S non-whitespace –\w word ; \W non-word –\d digit ; \D non-digit Trailing options can modify the behaviour: –/regexp/i … match case insensitive –/regexp/x … remove whitespace and comments –/regexp/e …if string is PHP code, evaluate it

Sys.Prog & Scripting - HW Univ13 Examples preg_match('/here\s*(\w+)/', 'match word after here test', $matches); $matches[1] is 'test' preg_match('/I like (?i:PHP)/', 'I like pHp'); ?i makes match against PHP case- insensitive preg_replace('/(\w)\w*\s*(\w+)/', '\2, \1.', array('Will Smith', 'John Doe')); Result: array ('Smith, W.', 'Doe, J.') preg_replace('/ /', '!', 'beware of this ') Result: 'beware of !this!'

Sys.Prog & Scripting - HW Univ14 Examples preg_split('{[+*/-]}', '3+5*9/2') ; Result: array ('3', '5', '9', '2'); preg_grep('/\.txt$/', $filenames); Result: array of filenames ending with.txt preg_quote('/usr/local/etc/resolv/conf', '/'); Creates a regular expression, matching exactly this string, escaping every '/' Many, many more features...

Sys.Prog & Scripting - HW Univ15 Example: Credit Card Validation <?php // Credit Card Validator from // "Programming PHP", Rasmus Lerdorf et al, Chapter 4 function isValidCreditCard ($inCardNumber, $inCardType) { // assume it is ok $isValid = true; // strip all non-numbers $inCardNumber = ereg_replace('[^0-9]', '', $inCardNumber); // $inCardNumber = ereg_replace('[^[:digit:]]', '', $inCardNumber);

Sys.Prog & Scripting - HW Univ16 Example: Credit Card Validation // make sure card number and type match switch ($inCardType) { case 'mastercard': $isValid = ereg('^5[1-5].{14}$', $inCardNumber); break; case 'visa': $isValid = ereg('^4.{15}|^4.{12}$', $inCardNumber); break; case 'amex': $isValid = ereg('^3[47].{13}$', $inCardNumber); break; case 'discover': $isValid = ereg('^6011.{12}$', $inCardNumber); break; case 'diners': $isValid = ereg('^30[0-5].{11}|^3[68].{12}$', $inCardNumber); break; }

Sys.Prog & Scripting - HW Univ17 Example: Credit Card Validation if ($isValid) { // reverse the string $inCardNumber = strrev($inCardNumber); // total the digits in the number, doubling in odd positions $theTotal = 0; for ($i = 0; $i <strlen($inCardNumber); $i++) { $theAdder = (int) $inCardNumber[$i]; // double if odd numbered position if ($i % 2) { $theAdder = $theAdder << 1; if ($theAdder > 9) { $theAdder -= 9; } } $theTotal += $theAdder; } // Valid cards will divide evenly by 10 $isValid = (($theTotal % 10) == 0); } return $isValid; } ?>

Sys.Prog & Scripting - HW Univ18 Wrapper: Credit Card Validation... Credit card validation <?php include 'cc_valid.php'; $debug = 1; $cc_number = $_GET['number']; $cc_type = $_GET['type']; $self = basename($_SERVER['PHP_SELF']); if ($debug){ print " \n"; print " Received: number=$cc_number;type=$cc_type \n"; print " \n"; }

Sys.Prog & Scripting - HW Univ19 Wapper: Credit Card Validation // did we receive a number to validate if ($cc_number == "" || $cc_type == "") { // No: show the form to enter one ?> Enter Number and Type of your Card: " method="get"> Credit Card Number: Credit Card Type:

Sys.Prog & Scripting - HW Univ20 Wrapper: Credit Card Validation <?php } else { // Yes: check the number ?> The result of validation is: <?php if (isValidCreditCard ($cc_number, $cc_type)) { echo "The credit card $cc_number of type $cc_type is valid. Congrats!"; } else { echo "I am sorry, but the credit card $cc_number of type $cc_type is NOT valid."; } ?>