Reg Ex Program
Reg Ex Program
Reg Ex Program
com/server-side-form-validation-regular-expressions/
https://www.javatpoint.com/php-interview-questions
Defining Strings
In PHP, we can define string in multiple ways. Let’s discuss them one by one:
1.Single Quote Strings
We can declare strings using single quotes. When we use single quotes to define a string and print them, PHP
interpreter does not parse the string and print it as it is. Consider:
$many = 9;
$sentence = 'Our solar system contains $many planets';
print $sentence;
Output:
Our solar system contains $many planets
2.Double Quote Strings
PHP also allows declaring strings in double quotes. At the time of printing of a double quote string, it is
parsed and if there are any variables, they are replaced. Consider:
$many = 9;
$sentence = "Our solar system contains $many planets";
print $sentence;
Output:
Our solar system contains 9 planets
3.heredoc
Heredoc method of defining string in PHP is used when we have very complex strings.
The heredoc supports all the features of double quotes. It also allows strings to be defined in more than one
line without string concatenation.
We use heredoc syntax when there is a complex string spread over multiple lines. In this syntax, we may use
double quotes inside the string sequence without escaping them.
Example:
$name = "Bootsity";
$here_doc = <<<EOT
This is $name website
for PHP, Laravel and Angular Tutorials
EOT;
echo $here_doc;
Output:
This is Bootsity website
for PHP, Laravel and Angular Tutorials
4.nowdoc
The Nowdoc string definition method in PHP is like the heredoc method but it works like the way single
quotes work.
For nowdoc, no parsing takes place at time of printing inside the Nowdoc blocks.
Nowdoc string definition comes handy when we are working with raw data that do not need to be parsed
(variables not expanded). Consider:
$name = "Bootsity";
$here_doc = <<<'EOT'
This is $name website
for PHP, Laravel and Angular Tutorials
EOT;
echo $here_doc;
Output:
This is $name website
for PHP, Laravel and Angular Tutorials
Only difference between heredoc's and nowdoc's syntax is that nowdoc's starting identifier is surrounded by
single quotes.
Concatenating strings
In PHP, string concatenation is done using concatenation operator, which is denoted by a dot (.)
Example:
$str = "Bootsity"." Tutorials"
echo $str; // will print - Bootsity Tutorials
5. Comments
Comments are strings that we write in our programs to give information about the current code. Comments
are meta-data about code and are not executed at run-time. PHP supports two type of comments:
1. Single line comments and
2. Multi line comments.
<?php
/* Multiline comment
it spreads across multiple lines
*/
Regular Expressions
One of the most important tools in any programming language is regular expressions,
because it searches for patterns in strings.
Where regular expressions can be used? Almost everywhere. For form validation, browser
detection, spam filtering, to check the strength of passwords, and so much more.
preg_match is built-in PHP function, that searches for a match to regular expressions
within strings. If it finds a match, it returns true, otherwise it returns false.
For example:
<?php
// The regex here is the word 'go'.
$regex = "/go/";
// We search for a match inside this string.
$string = "you gotta give the go kart a try";
// preg_match returns true or false.
if(preg_match($regex, $string, $match))
{
echo "We found a match to the expression: " . $match[0];
}
else
{
echo "We found no match.";
}
?>
Result:
We found a match to to the expression: go
preg_match searches for a string that matches the regular expression ($regex) in the
string ($string), and the first match it finds is stored as the first item of
the $match array.
If we change the string to something that doesn't match the pattern, preg_match will
return false.
# The i modifier
Regular expressions are by default case sensitive. This means that the regular
expressions /chr*/ is different from /Chr*/, only because the the first expression
starts with a lowercase 'c' while the second starts with a capital 'C'. But we can change
this behavior by adding the i modifier, right after the closing delimiter of the regular
expression.
So, the regular expression:
$regex = "/Chr*/i";
will match both 'Chrome' as well as 'chrome'.
Result:
Array
(
[0] => reg
[1] => reg
[2] => reg
)
# Meta what? Meta character!
Metacharacters are characters that have special meaning in regular expressions.
Let's learn our first 3 metacharacters:
metachara
cter matches
. The dot metacharacter matches any character except for a new line
\. Simply a dot
In some cases, you don't need to escape the metacharacters, because the regular
expressions are smart enough to know where to use the metacharacters in their literal
meaning. On the other hand, it can't hurt to add the backslash whenever you want to
use metacharacters in their literal meaning. So, use the backslash if you're not sure, it
probably won't hurt you.
# Character sets
We can use character sets to specify a range of characters to which we want to find a match between square
brackets.
The character
set matches
[ab] a or b
[abc] a, b or c
The caret (^) symbol represents the start of the string, but when it is used inside the square brackets it
indicates the negation of the character set.
For example, if [a-z] means the range of letters from a to z, than [^a-z] with the caret symbol inside the
brackets, means every character that is not in the set of lowercase letters.
Let's see some more examples:
The character
set matches
We have shortcuts for some of the most commonly used character sets.
The
shorthand matches
$regex = "/\s\w\s\d\d\d\d$/";
Searches for a pattern that matches white space, a word character, another white space, and than 4 digits.
Let's test the expression with the following code:
$regex = "/\s\w\s\d\d\d\d/";
We found the the pattern of a space, followed by a word character, followed by 4 digits at the end of the
string.
For example, in order to find a match to the string "Mississippi", we can use the following expression:
1$regex = "/Mis{2}is{2}ip{2}i/";
The
quantifier Searches for
For example, we can find a match to both "color" and "colour" by using the following regular expression:
$regex = "colou{0,1}r";
The
quantifier Searches for
+ at least 1 time
? zero or 1 time
For example, the following expression can match both "color" and "colour".
$regex = "colou?r";
Since the "?" metacharacter makes the one character that it follows optional, the regular expression finds a
match with or without the "u".
For example, I would like to replace the colors of both cats (which are found inside span elements) with the
string 'M@#!'in the following sentence.
To get what we want, we need to make the expression lazy. We can make the expression lazy by adding the
'?' symbol right after the quantifier.
Let's precede the expression with the '?' symbol to make it lazy.
Result is:
Said the M@#! cat to the M@#! cat.
Every span is separately replaced.
In order to choose between several alternatives we need to put the pipe (|) symbol between the different
alternatives. For example,
To find a match to one of the strings 'png' or 'jpeg' we use the expression '/png|jpeg/'.
We can have more than two alternatives, '/png|jpeg|gif|bmp/'.
If we want to choose between 'jpg' and 'jpeg', we can add the expression 'jpeg' to the set: '/png|jpg|gif|bmp|
jpeg/'.
We can also make the 'e' in 'jpeg' optional, by adding the '?' symbol right after it: '/png|jpe?g|gif|bmp/'.
Pay attention to the parentheses around the set of file extensions. The parentheses separate the extensions
from the rest of the expression, so the first alternative in the set is 'png' and not '([A-Za-z0-9-_.])+\.png'.
In the previous section, we saw how to write a set of options when the order does not matter, but how can we
search for matches when the order does matter?
To find a perfect match, we need to modify the regex a little bit, so it can only match the right options.
$regex = "/^the sum of (2( and 3)|3( and 2)) is 5$/";
Let's test the regex:
Result is:
In the following example, we take the dates in the European date format and re-format
them into the American date format.
$string = "16-04-2016";
$regex = "/([0-9]{1,2})-([0-9]{1,2})-([0-9]{4})/";
//The first group references the day
//The second group references the month
$replace = "$2-$1-$3";
//Replace the first group with the second
Result is:
04-16-2016
$string = "16-04-2016";
$regex = "/([0-9]{1,2})-([0-9]{1,2})-(?:[0-9]{4})/";
$replace = "$2-$1-$3";
For example, we can improve the performance of the regex that searches for images by
adding the non-capturing group:
$regex = "/^(?:[A-Za-z0-9-_.])+\.(?:png|jpe?g|gif|bmp)$/";
# The search for strings that don't match
Sometimes we may be intersted only in those strings that do not match the regular
expression, and in these cases we will precede the PHP function with the "not operator"
(!) in order to reverse the result of the boolean expression.
Better done than said. In the following example, we want to find a match to those
strings that do not contain the string "fowl":
$regex = "/fowl/";
$string = "Birds of a feather flock together.";
// In order to search for strings that don't match
// we precede the PHP function with the not operator, "!"
if(!preg_match($regex, $string, $match))
{
echo "No match";
}
else
{
echo "There is a match";
}
Result is:
No match
In the following example, we replace all the wrong forms of the word 'misspelled' with
the correct form.
$regex = "/miss?pp?ell?e?d/";
$replace = "misspelled";
$string = "He mispeled the word in all of his emails.";
Result is:
He misspelled the word in all of his emails.
preg_split is the built-in PHP function that we use when we want to split a string by
regular expression. It has the following syntax:
preg_split($regex, $string);
$regex - the expression that we search for, and want to split at.
$string - the string in which we search for the expression.
In the following example we want to split at the comma followed by any number of
spaces.
$regex = "/,\s+/";
$string = "html, css, javascript, php";
Result is:
Array
(
[0] => html
[1] => css
[2] => javascript
[3] => php
)
preg_grep searches for matches inside arrays, and brings back an array that is
consisted only of matching items.
The syntax:
preg_grep($pattern, $array);
$array stands for the array in which we search for matching items.
In the following example, we serch inside the $cars array for items that start with 't'
(lower or upper case):
$models = array("Bentley", "Tesla", "Maserati", "toyota", "Subaru",
"Alpha");
Result is:
Array
(
[1] => Tesla
[3] => toyota
)
w3_example.html
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
w3_example.php
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
</body>
</html>
https://stackoverflow.com/questions/6295141/server-not-parsing-html-as-php?
noredirect=1&lq=1
https://onlinewebapplication.com/server-side-form-validation-regular-expressions/