Friday, 29 December 2017

PHP The Good Part With Regular Expressions

Today we are going to work with php regluar expressions the good part of php, we use this expression pettern to gain text in a string, sometime we use this to validate email if it contain @ symbol or not.

The way you implement regular expression in other programming language does look alike to other languages.
For a complete reference,
see http://us2.php.net/manual/en/ref.pcre.php.

If are going to use Perl regular expressions on this excecis that will include forward slash '/' the the pattern.

For you find a matching pattern somewhere in a string
take a look at the example

if (preg_match("/ard/", "Harding"))
{
echo "Matches";
}
else
{
echo "No match";
}

Special symbols

\d any digit (0-9)
\s any white space (space, tab, EOL)
\w any word char (a-z, A-Z, 0-9, _)
. any character except EOL
[abc] a, b, or c
[^a-z] not any char between a and z


{3} match only three of these
? match zero or one character
* match zero or many characters
+ match one or many characters
^abc match at the very beginning of the string
abc$ match at the very end of the string


Email address pattern example

$email = 'first_name.last_name@domain.Com';
$regexp = "/^[\w.]+@[\w.]+[a-z]{2,4}$/i"; // i switch for case-insensitive match

if (preg_match($regexp, $email))
{
echo "Match email";
}

Remembering matched patterns


if (preg_match('/(\d\d):(\d\d) (am|pm)/', '03:15 pm', $matches)) {
echo "Hour: $matches[1]\n"; // 03
echo "Min: $matches[2]\n"; // 15
echo "Ending: $matches[3]\n"; // pm
}

Match all occurrences

preg_match_all('/.ar/', 'the car was far from the bar', $matches);
print_r($matches[0]); // Prints car, far, bar

No comments:

Post a Comment