Showing posts with label Advanced PHP Regular Expressions. Show all posts
Showing posts with label Advanced PHP Regular Expressions. Show all posts

Sunday, 25 August 2013

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 following result.
\$40 for a g3\/400

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 following result.
Found food is pasta
Found food is potatoes

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 flags:
  • PREG_SPLIT_NO_EMPTY: If this flag is set, only non-empty pieces will be returned by preg_split().
  • PREG_SPLIT_DELIM_CAPTURE: If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
  • PREG_SPLIT_OFFSET_CAPTURE: If this flag 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 following result.
123
456
789
000 

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 paramerter $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 following result.
Copyright 2000

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: is the default if the optional order parameter is not included. 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: will order the array a bit differently than the default setting. $pattern_array[0] will contain elements matched by the first parenthesized 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 following result.
John Poul
PHP Guru

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 following result.
Match found!

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 alongwith convered 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 following result:
[Pp] [Hh] [Pp] [ ] [44] [..] [00]

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 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 following result
123
456
789
000 

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 following result
© 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 following result
Invalid password! Passwords must be from 8 - 10 chars

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 following result
Copyright 2000

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 following result
Found a .com
Found a .com and reg = .com