Regular expression Basic tips

Regular expression Basic tips

PHP has two set of regular expression
1. perl compatible
2. Posix extended

First we will take Perl-Compatible for our discussion
The syntax for patten used for these functions resembles closely with the Perls regular expression syntax.

First we will start with simple matches

- ‘hai’ will directly match ‘hai’
let us proceed with two special symbols ‘^’ & ‘$’

^ - do the match from the start
‘^hello’ will match the any string start with the word ‘hello’
$- matches the end of the string
‘hello$’ - will match the any string ends with hello
let us combine both ‘^hello$’ this will match a string that should start with ‘hello’
and end with ‘hello’ ie it should only contain ‘hello’.

Now we will take some more symbols *,+,?

* - matches 0 or more quantifier
+ - matches 1 or more quantifier
? - matches 0 or 1 quantifier

‘as*’ - matches a string with ‘a’ followed by 0 or any number of ’s’
‘as+’ - matches a string with ‘a’ followed by at least one ’s’

‘as?’ - matches the string with ‘a’ followed by 0 or 1 ’s’.

symbols {}- min/max quantifier

‘as{3}’ matches ‘asss’ ie ‘a’ and exactly 3 ’s’

‘as{2,3} matches ‘a’ followed by 2 to 3 ’s’

‘as{2,} matches ‘a’ followed by minimum 2 to n number of ’s’

‘as{,3}’ matches a followed by 0 to maximum 3 ’s’

period ‘.’ quantifier

‘.’ - matches any character

‘a.*’ will match a followed by any character

[] - class definition quantifier

‘[0-9]’ - matches digits from 0-9
‘[a-z]’ - matches characters from a-z
‘[A-Z]’ - matches characters from A-Z

ex

preg_match(’/[0-9]{2}-[0-9]{2}-[0-9]{4}/’,$string)

will match formats like 12-12-2007

preg_match(’/[0-9a-zA-Z]*/’,$string)

will match digits and alphabets

Splitting String to character Array

<?php
$str = ’string’;
$chars = preg_split(’//’, $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.