The largest Interview Solution Library on the web


« Previous | 1 | 2 | 3 | Next »

PHP ─ Regular Expression


Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside another string, you can replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.
  • POSIX Regular Expressions
  • PERL Style Regular Expressions
POSIX Regular Expressions

The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.

The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.

Let us discuss a few concepts being used in POSIX regular expression. After that, we will introduce you to regular expression related functions.

Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
ExpressionDescription
[0-9]It matches any decimal digit from 0 through 9.
[a-z]It matches any character from lowercase a through lowercase z.
[A-Z]It matches any character from uppercase A through uppercase Z.
[a-Z]It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

Quantifiers

The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.
ExpressionDescription
p+It matches any string containing at least one p.
p*It matches any string containing zero or more p's.
p?It matches any string containing zero or more p's. This is just an alternative way to use p*.
p{N}It matches any string containing a sequence of N p's
p{2,3}It matches any string containing a sequence of two or three p's.
p{2, }It matches any string containing a sequence of at least two p's.
p$It matches any string with p at the end of it.
^pIt matches any string with p at the beginning of it.
Examples

Following examples will clear your concepts about matching characters.
ExpressionDescription
[^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z.
p.pIt matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$It matches any string containing exactly two characters.
<b>(.*)</b>It matches any string enclosed within and .
p(hp)*It matches any string containing a p followed by zero or more instances of the sequence hp.
Predefined Character Ranges

For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set:
ExpressionDescription
[[:alpha:]]It matches any string containing alphabetic characters aA through zZ.
[[:digit:]]It matches any string containing numerical digits 0 through 9.
[[:alnum:]]It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
[[:space:]]It matches any string containing a space.
PHP's Regexp POSIX Functions

PHP currently offers seven functions for searching strings using POSIX-style regular expressions:
FunctionDescription
ereg()The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
ereg_replace()The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
eregi()The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
eregi_replace(The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
split()The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
spliti()The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
sql_regcase()The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.
PHP ─ Function ereg()

Syntax

int ereg(string pattern, string originalstring, [array regs]);

Definition and Usage

The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise. The search is case sensitive in regard to alphabetical characters.

The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression.
Return Value
  • It returns true if the pattern is found, and false otherwise.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$email_id = "admin@tutorialspoint.com";
$retval = ereg("(\.)(com$)", $email_id);
if( $retval == true )
{
echo "Found a .com<br>";
}
else
{
echo "Could not found a .com<br>";
}
$retval = ereg(("(\.)(com$)"), $email_id, $regs);
if( $retval == true )
{
echo "Found a .com and reg = ". $regs[0];
}
else
{
echo "Could not found a .com";
}
?>

This will produce the following result −

Found a.com
Found a.com and reg=.com

PHP ─ Function ereg_replace()

Syntax

string ereg_replace (string pattern, string replacement, string
originalstring);

Definition and Usage

The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. The ereg_replace() function operates under the same premises as ereg(), except that the functionality is extended to finding and replacing pattern instead of simply locating it.

Like ereg(), ereg_replace() is case sensitive.

Return Value
  • After the replacement has occurred, the modified string will be returned.
  • If no matches are found, the string will remain unchanged.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$copy_date = "Copyright 1999";
$copy_date = ereg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>

This will produce the following result −

Copyright 2000

PHP ─ Function eregi()

Syntax

int eregi(string pattern, string string, [array regs]);

Definition and Usage

The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. Eregi() can be particularly useful when checking the validity of strings, such as passwords.

The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression.

Return Value
  • It returns true if the pattern is validated, and false otherwise.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$password = "abc";
if (! eregi ("[[:alnum:]]{8,10}", $password))
{
print "Invalid password! Passwords must be from 8 - 10 chars";
}
else
{
print "Valid password";
}
?>

This will produce the following result −

Invalid password! Passwords must be from 8 - 10 chars

PHP ─ Function eregi_replace()

Syntax

string eregi_replace (string pattern, string replacement, string
originalstring);

Definition and Usage

The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.

Return Value
  • After the replacement has occurred, the modified string will be returned.
  • If no matches are found, the string will remain unchanged.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$copy_date = "Copyright 2000";
$copy_date = eregi_replace("([a-z]+)", "&Copy;", $copy_date);
print $copy_date;
?>

This will produce the following result −

& Copy:2000

PHP ─ Function split()

Syntax

array split (string pattern, string string [, int limit])

Definition and Usage

The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.

The optional input parameter limit is used to signify the number of elements into which the string should be divided, starting from the left end of the string and working rightward. In cases where the pattern is an alphabetical character, split() is case sensitive.

Return Value
  • Returns an array of strings after splitting up a string.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php $ip = "123.456.789.000"; // some IP address
$iparr = split ("\.", $ip);
print "$iparr[0] <br />";
print "$iparr[1] <br />" ;
print "$iparr[2] <br />" ;
print "$iparr[3] <br />" ;
?>

This will produce the following result −

123
456
789
000

PHP ─ Function spliti()

Syntax

array spliti (string pattern, string string [, int limit])

Definition and Usage

The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive. Case-sensitive characters are an issue only when the pattern is alphabetical. For all other characters, spliti() operates exactly as split() does.

Return Value
  • Returns an array of strings after splitting up a string.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$ip = "123.456.789.000"; // some IP address
$iparr = spliti ("\.", $ip, 3);
print "$iparr[0] <br />";
print "$iparr[1] <br />" ;
print "$iparr[2] <br />" ;
print "$iparr[3] <br />" ;
?>

This will produce only three strings as we have limited number of strings to be produced.

123
456
789.000

PHP ─ Function sql_regcase()

Syntax

string sql_regcase (string string)

Definition and Usage

The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.

If the alphabetical character has both an uppercase and a lowercase format, the bracket will contain both forms; otherwise the original character will be repeated twice. Return Value
  • Returns a string of bracketed expression along with the converted character.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$version = "php 4.0";
print sql_regcase($version);
?>

This will produce the following result −

[Pp][Hh][Pp]4.0

PERL Style Regular Expressions

Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.

Let us discuss a few concepts being used in PERL regular expressions. After that, we will introduce you with regular expression related functions.
Metacharacters

A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

For instance, you can search for large money sums using the '\d' metacharacter:/([\d]+)000/, Here \d will search for any string of numerical character.

Following is the list of metacharacters which can be used in PERL Style Regular Expressions.
CharacterDescription
.a single character
\sa whitespace character (space, tab, newline)
\Snon-whitespace character
\da digit (0-9)
\Da non-digit
\wa word character (a-z, A-Z, 0-9, _)
\Wa non-word character
[aeiou]matches a single character in the given set
[^aeiou]matches a single character outside the given set
(foo|bar|baz)matches any of the alternatives specified
Modifiers

Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.
ModifierDescription
iMakes the match case insensitive
mSpecifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
oEvaluates the expression only once
sAllows use of . to match a newline character
xAllows you to use white space in the expression for clarity
gGlobally finds all matches
cgAllows a search to continue even after a global match fails
PHP's Regexp PERL Compatible Functions

PHP offers the following functions for searching strings using Perl-compatible regular expressions:
FunctionDescription
preg_match()The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all()The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split()The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep()The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote()Quote regular expression characters
PHP ─ Function preg_match()

Syntax

int preg_match (string pattern, string string [, array pattern_array], [, int
$flags [, int $offset]]]);

Definition and Usage

The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.

If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns contained in the search pattern, if applicable.

If this flag is passed as PREG_OFFSET_CAPTURE, for every occurring match the appendant string offset will also be returned

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.

Return Value
  • Returns true if pattern exists, and false otherwise.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$line = "Vi is the greatest word processor ever created!";
// perform a case-Insensitive search for the word "Vi"
if (preg_match("/\bVi\b/i", $line, $match)) :
print "Match found!";
endif;
?>

This will produce the following result −

Match found!

PHP ─ Function preg_match_all()

Syntax

int preg_match_all (string pattern, string string, array pattern_array [, int
order]);

Definition and Usage

The preg_match_all() function matches all occurrences of pattern in string.

It will place these matches in the array pattern_array in the order you specify using the optional input parameter order. There are two possible types of order –
  • PREG_PATTERN_ORDER −REG_PATTERN_ORDERe matches in the array pattern_array in the od. PREG_PATTERN_ORDER specifies the order in the way that you might think most logical; $pattern_array[0] is an array of all complete pattern matches, $pattern_array[1] is an array of all strings matching the first parenthesized regexp, and so on.
  • PREG_SET_ORDER −REG_SET_ORDERRDERe matches in the array pattern_array in the od. PREG_PATTERN_ORDER specifies the order in the way that you migparenthesized regexp, $pattern_array[1] will contain elements matched by the second parenthesized regexp, and so on.
Return Value
  • Returns the number of matchings.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$userinfo = "Name: <b>John Poul</b> <br> Title: <b>PHP Guru</b>";
preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n";
?>

This will produce the following result –

John Poul
PHP Guru

PHP ─ Function preg_replace()

Syntax

mixed preg_replace (mixed pattern, mixed replacement, mixed string [, int limit
[, int &$count]] );

Definition and Usage

The preg_replace() function operates just like POSIX function ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.

The optional input parameter limit specifies how many matches should take place.

If the optional parameter $count is passed, then this variable will be filled with the number of replacements done.

Return Value
  • After the replacement has occurred, the modified string will be returned.
  • If no matches are found, the string will remain unchanged.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$copy_date = "Copyright 1999";
$copy_date = preg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>

This will produce the following result −

Copyright 2000

PHP ─ Function preg_split()

Syntax

array preg_split (string pattern, string string [, int limit [, int flags]]); Definition and Usage

The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.

If the optional input parameter limit is specified, then only limit number of substrings are returned.

flags can be any combination of the following types –
  • PREG_SPLIT_NO_EMPTY −REG_SPLIT_NO_EMPTYmbination of the following fied, then only limit number of s
  • PREG_SPLIT_DELIM_CAPTURE −REG_SPLIT_DELIM_CAPTUREtion of the following fied, then only limit number of substrings are returned.as input p
  • PREG_SPLIT_OFFSET_CAPTURE −REG_SPLIT_Oag is set, for every occurring match the appendant string offset will also be returned. Return Value

  • Returns an array of strings after splitting up a string.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$ip = "123.456.789.000"; // some IP address
$iparr = split ("/\./", $ip);
print "$iparr[0] <br />";
print "$iparr[1] <br />" ;
print "$iparr[2] <br />" ;
print "$iparr[3] <br />" ;
?>

This will produce the following result −

123.456.789.000

PHP ─ Function preg_grep()

Syntax

array preg_grep ( string $pattern, array $input [, int $flags] );

Definition and Usage

Returns the array consisting of the elements of the input array that match the given pattern.

If flag is set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Return Value
  • Returns an array indexed using the keys from the input array.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$foods = array("pasta", "steak", "fish", "potatoes");
// find elements beginning with "p", followed by one or more letters.
$p_foods = preg_grep("/p(\w+)/", $foods);
print "Found food is " . $p_foods[0];
print "Found food is " . $p_foods[1];
?>

This will produce the following result −

Found food is pasta Found food is

PHP ─ Function preg_quote()

Syntax

string preg_quote ( string $str [, string $delimiter] );

Definition and Usage

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax.

Return Value
  • Returns the quoted string.
Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords;
?>

This will produce the following result –

\$40 for a g3\400';
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com