Regular expressions
Introduction

Regular expression is search for patterns in a given text.
like 


$test_string = 'amit123';


you can see amit is in 4 letter and 123 is 3 digit. this is a way of searching patterns for given text.
In Regular expression term we can write ([A-Z]{3}|[0-9]{4}).

Some usefull regular expression

Regular Expression

Will match…

php

The string "php"

^php

"php" at the start of a string

php$

"php" at the end of a string

^php$

"php" when it is alone on a string

[abc]

a, b, or c

[a-z]

Any lowercase letter

[^A-Z]

Any character that is not a uppercase letter

(gif|jpg)

Matches either “gif” or “jpeg”

[a-z]+

One or more lowercase letters

[0-9.-]

Ð┬Ény number, dot, or minus sign

^[a-zA-Z0-9_]{1,}$

Any word of at least one letter, number or _

([wx])([yz])

wy, wz, xy, or xz

[^A-Za-z0-9]

Any symbol (not a number or a letter)

([A-Z]{3}|[0-9]{4})

Matches three letters or four numbers

 

PHP regular expression functions

Some usefull php regular expression function are.

preg_match()

preg_match_all()

preg_replace()

Example of Regular expression

<?php

$test_string = 'shir2343';

echo preg_match('([A-Z]{3}|[0-9]{4})', $test_string);

?>


Previous
Next