Chapter 2 - HTML Forms and Server-Side Scripting
Chapter 2 - HTML Forms and Server-Side Scripting
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Syntax
if (condition) {
//code to be executed if this condition is true;
} elseif (condition) {
//code to be executed if first condition is false and this condition is true;
} else {
//code to be executed if all conditions are false;
}
Example
Output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the
current time is less than 20. Otherwise it will output “Have a good night!”:
<?php
$t = date(“H”);
if ($t < “10”) {
echo “Have a good morning!”;
} elseif ($t < “20”) {
echo “Have a good day!”;
} else {
echo “Have a good night!”;
}
?>
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Example
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops. Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Example Explained
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
Example
<?php
$x = 0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100 - Continue the loop as long as $x is less than or equal to 100
$x+=10; - Increase the loop counter value by 10 for each iteration
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Note: In a do...while loop the condition is tested AFTER executing the statements within the
loop. This means that the do...while loop will execute its statements at least once, even if the
condition is false. See example below.
This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
Examples
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 10; - Continue the loop as long as $x is less than or equal to 10
$x++ - Increase the loop counter value by 1 for each iteration
Example
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100; - Continue the loop as long as $x is less than or equal to 100
$x+=10 - Increase the loop counter value by 10 for each iteration
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
The following example will output both the keys and the values of the given array ($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch statement. The break statement can also be used to jump out of a loop.
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Break and Continue in While Loop
Break Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>
Continue Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>
There is no guarantee that the information provided by the user is always correct. PHP validates
the data at the server-side, which is submitted by HTML form. You need to validate a few
things:
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length
Empty String
The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.
1. if (empty ($_POST["name"])) {
2. $errMsg = "Error! You didn't enter the Name.";
3. echo $errMsg;
4. } else {
5. $name = $_POST["name"];
6. }
Validate String
The code below checks that the field will contain only alphabets and whitespace, for example -
name. If the name field does not receive valid input from the user, then it will show an error
message:
1. $name = $_POST ["Name"];
2. if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
3. $ErrMsg = "Only alphabets and whitespace are allowed.";
4. echo $ErrMsg;
5. } else {
6. echo $name;
7. }
Validate Number
The below code validates that the field will only contain a numeric value. For example - Mobile
no. If the Mobile no field does not receive numeric data from the user, the code will display an
error message:
1. $mobileno = $_POST ["Mobile_no"];
2. if (!preg_match ("/^[0-9]*$/", $mobileno) ){
3. $ErrMsg = "Only numeric value is allowed.";
4. echo $ErrMsg;
5. } else {
6. echo $mobileno;
7. }
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate the
email address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form. If the
field does not contain a valid email address, then the code will display an error message:
1. $email = $_POST ["Email"];
2. $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
3. if (!preg_match ($pattern, $email) ){
4. $ErrMsg = "Email is not valid.";
5. echo $ErrMsg;
6. } else {
7. echo "Your valid email address is: " .$email;
8. }
The input length validation restricts the user to provide the value between the specified range, for
Example - Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input:
1. $mobileno = strlen ($_POST ["Mobile"]);
2. $length = strlen ($mobileno);
3.
4. if ( $length < 10 && $length > 10) {
5. $ErrMsg = "Mobile must have 10 digits.";
6. echo $ErrMsg;
7. } else {
8. echo "Your Mobile number is: " .$mobileno;
9. }
Validate URL
The below code validates the URL of website provided by the user via HTML form. If the field
does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".
1. $websiteURL = $_POST["website"];
2. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
3. $websiteErr = "URL is not valid";
4. echo $websiteErr;
5. } else {
6. echo "Website URL is: " .$websiteURL;
7. }
The below code validates that the user click on submit button and send the form data to the
server one of the following method - get or post.
1. if (isset ($_POST['submit']) {
2. echo "Submit button is clicked.";
3. if ($_SERVER["REQUEST_METHOD"] == "POST") {
4. echo "Data is sent using POST method ";
5. }
6. } else {
7. echo "Data is not submitted";
8. }
Note: Remember that validation and verification both are different from each other.
Now we will apply all these validations to an HTML form to validate the fields. Thereby you can
learn in detail how these codes will be used to validation form.
Create a registration form using HTML and perform server-side validation. Follow the below
instructions as given:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. .error {color: #FF0001;}
6. </style>
7. </head>
8. <body>
9.
10. <?php
11. // define variables to empty values
12. $nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";
13. $name = $email = $mobileno = $gender = $website = $agree = "";
14.
15. //Input fields validation
16. if ($_SERVER["REQUEST_METHOD"] == "POST") {
17.
18. //String Validation
19. if (empty($_POST["name"])) {
20. $nameErr = "Name is required";
21. } else {
22. $name = input_data($_POST["name"]);
23. // check if name only contains letters and whitespace
24. if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
25. $nameErr = "Only alphabets and white space are allowed";
26. }
27. }
28.
29. //Email Validation
30. if (empty($_POST["email"])) {
31. $emailErr = "Email is required";
32. } else {
33. $email = input_data($_POST["email"]);
34. // check that the e-mail address is well-formed
35. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
36. $emailErr = "Invalid email format";
37. }
38. }
39.
40. //Number Validation
41. if (empty($_POST["mobileno"])) {
42. $mobilenoErr = "Mobile no is required";
43. } else {
44. $mobileno = input_data($_POST["mobileno"]);
45. // check if mobile no is well-formed
46. if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
47. $mobilenoErr = "Only numeric value is allowed.";
48. }
49. //check mobile no length should not be less and greator than 10
50. if (strlen ($mobileno) != 10) {
51. $mobilenoErr = "Mobile no must contain 10 digits.";
52. }
53. }
54.
55. //URL Validation
56. if (empty($_POST["website"])) {
57. $website = "";
58. } else {
59. $website = input_data($_POST["website"]);
60. // check if URL address syntax is valid
61. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z0-9+&@#\/%=~_|]/i",$website)) {
62. $websiteErr = "Invalid URL";
63. }
64. }
65.
66. //Empty Field Validation
67. if (empty ($_POST["gender"])) {
68. $genderErr = "Gender is required";
69. } else {
70. $gender = input_data($_POST["gender"]);
71. }
72.
73. //Checkbox Validation
74. if (!isset($_POST['agree'])){
75. $agreeErr = "Accept terms of services before submit.";
76. } else {
77. $agree = input_data($_POST["agree"]);
78. }
79. }
80. function input_data($data) {
81. $data = trim($data);
82. $data = stripslashes($data);
83. $data = htmlspecialchars($data);
84. return $data;
85. }
86. ?>
87.
88. <h2>Registration Form</h2>
89. <span class = "error">* required field </span>
90. <br><br>
91. <form method="post" action="<?php echo htmlspecialchars($_SERVER[
"PHP_SELF"]); ?>" >
92. Name:
93. <input type="text" name="name">
94. <span class="error">* <?php echo $nameErr; ?> </span>
95. <br><br>
96. E-mail:
97. <input type="text" name="email">
98. <span class="error">* <?php echo $emailErr; ?> </span>
99. <br><br>
100. Mobile No:
101. <input type="text" name="mobileno">
102. <span class="error">* <?php echo $mobilenoErr; ?> </span>
103. <br><br>
104. Website:
105. <input type="text" name="website">
106. <span class="error"><?php echo $websiteErr; ?> </span>
107. <br><br>
108. Gender:
109. <input type="radio" name="gender" value="male"> Male
110. <input type="radio" name="gender" value="female"> Female
111. <input type="radio" name="gender" value="other"> Other
112. <span class="error">* <?php echo $genderErr; ?> </span>
113. <br><br>
114. Agree to Terms of Service:
115. <input type="checkbox" name="agree">
116. <span class="error">* <?php echo $agreeErr; ?> </span>
117. <br><br>
118. <input type="submit" name="submit" value="Submit">
119. <br><br>
120. </form>
121. <?php
122. if(isset($_POST['submit'])) {
123. if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderE
rr == "" && $websiteErr == "" && $agreeErr == "") {
124. echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </
h3>";
125. echo "<h2>Your Input:</h2>";
126. echo "Name: " .$name;
127. echo "<br>";
128. echo "Email: " .$email;
129. echo "<br>";
130. echo "Mobile No: " .$mobileno;
131. echo "<br>";
132. echo "Website: " .$website;
133. echo "<br>";
134. echo "Gender: " .$gender;
135. } else {
136. echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
137. }
138. }
139. ?>
140.
141. </body>
142. </html>
When the above code runs on a browser, the output will be like the screenshot below:
filter_input ( int $type , string $var_name , int $filter = FILTER_DEFAULT , array|int $options
= 0 ) : mixed
The following example uses the filter_input() function to sanitize data for a search form:
<?php
?>
</form>
<?php
The form contains an input with type search and a submit button. When you enter a search term,
e.g., how to use the filter_input function and click the submit button; the form uses the GET
method to append the term query string to the URL, e.g.,
http://localhost/search.php?term=how+to+use+the+filter_input+function
http://localhost/search.php
The following filter_input() function returns null and doesn’t raise any error when you get
the term variable from the INPUT_GET:
<?php
var_dump($term);
Output:
NULL
<?php
var_dump($term);
Output:
string(0) ""
<?php
if (isset($_GET['term'])) {
var_dump($term);
}
Also, the filter_input() function doesn’t get the current values of the $_GET, $_POST, …
superglobal variables. Instead, it uses the original values submitted in the HTTP request. For
example:
<?php
var_dump($term);
Output:
NULL
On the other hand, the filter_var() function does read values from the current $_GET variable.
For example:
<?php
$_GET['term'] = 'PHP';
var_dump($term);
Output:
string(3) "PHP"
You can see in the above case the values can be posted to another site. Note that after the page
name we are using question mark ( ? ) to start the variable data pair and we are separating each
variable data pair with one ampersand ( & ) mark.
"Using GET or POST," if a form uses the GET method, the resulting URL is something like
http://www.sitename.com/phptutor/handle_form.php?title=Mr.&name=Larry%20Ullman...
This script will receive a variable and its value in the URL.
1 <!DOCTYPE html>
3 <html>
4 <head>
<title>Greetings!</title>
</head>
<body>
// Say "Hello".
</body>
</html>
form.html:
<?php
$genre = $_POST['genre'];
echo $genre;
After the user clicks the submit button in the above code, the form data is sent to the results.php
file. Since we used the POST method to submit the form, the results are stored in
the $_POST array. We can access the data of the input field by using $_POST[’genre’].
Here genre is the value we used in the name attribute of the <input> tag. Let’s now look at an
example. We can submit an array of data.
PHP Arrays
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values by referring
to an index number.
array();
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and
then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
Associative arrays are arrays that use named keys that you assign to them. It refers to an array
with strings as an index. Rather than storing element values in a strict linear index order, this
stores them in combination with key values.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still
have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
In this chapter, we will go through the following PHP array sort functions:
The following example sorts the elements of the $cars array in ascending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
form.html:
<form action='results.php' method='post'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<button name='subimt'>Submit Information</button>
</form>
results.php:
<?php
$cars = $_POST['cars'];
foreach($cars as $car):
echo $car."<br>";
endforeach;
print_r($cars);
Sample output:
Ferrari Testarossa
Lamborghini Gallardo
Ford Mustang
Honda Prius
Jeep Gladiator
Array
(
[0] => Ferrari Testarossa
[1] => Lamborghini Gallardo
[2] => Ford Mustang
[3] => Honda Prius
[4] => Jeep Gladiator
)
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to
the server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment
variable.
The PHP provides $_GET associative array to access all the sent information using GET
method.
Try out following example by putting the source code in test.php script.
<?php
if(isset($_GET['submit'])){
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET["name"]. "<br />";
echo "You are ". $_GET["age"]. " years old.";
exit();
}}?>
<html>
<body>
</body>
</html>
It will produce the following result −
The POST Method
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using
POST method.
Try out following example by putting the source code in test.php script.
<?php
if(isset($_POST['submit'])){
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}}?>
<html>
<body>
</body>
</html>
It will produce the following result −
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −
Let's begin with a brief overview of the commonly used PHP's built-in pattern-matching
functions before delving deep into the world of regular expressions.
preg_grep() Returns the elements of the input array that matched the pattern.
Note: The PHP preg_match() function stops searching after it finds the first match, whereas
the preg_match_all() function continues searching until the end of the string and find all possible
matches instead of stopping at the first match.
The following sections describe the various options available for formulating patterns:
Character Classes
Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A
character class always matches a single character out of a list of specified characters that means
the expression [abc] matches only a, b or c character.
Negated character classes can also be defined that match any character except those contained
within the brackets. A negated character class is defined by placing a caret (^) symbol
immediately after the opening bracket, like this [^abc].
You can also define a range of characters by using the hyphen (-) character inside a character
class, like [0-9]. Let's look at some examples of character classes:
The following example will show you how to find whether a pattern exists in a string or not
using the regular expression and PHP preg_match() function:
Example
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){
echo "Match found!";
} else{
echo "Match not found.";
}
?>
Similarly, you can use the preg_match_all() function to find all matches within a string:
Example
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Tip: Regular expressions aren't exclusive to PHP. Languages such as Java, Perl, Python, etc. use
the same notation for finding patterns in text.
The following example will show you how to find and replace space with a hyphen character in a
string using regular expression and PHP preg_replace() function:Example
<?php
$pattern = "/\s/";
$replacement = "-";
$text = "Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
// Replace only spaces
echo str_replace(" ", "-", $text);
?>
Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety of fashions. But
what if you want to match on more than one character? For example, let's say you want to find
out words containing one or more instances of the letter p, or words containing at least two p's,
and so on. This is where quantifiers come into play. With quantifiers you can specify how many
times a character in a regular expression should match.
The following table lists the various ways to quantify a particular pattern:
p{2,3} Matches at least two occurrences of the letter p, but not more than three
occurrences of the letter p.
The regular expression in the following example will splits the string at comma, sequence of
commas, whitespace, or combination thereof using the PHP preg_split() function:
Example
<?php
$pattern = "/[\s,]+/";
$text = "My favourite colors are red, green and blue";
$parts = preg_split($pattern, $text);
Position Anchors
There are certain situations where you want to match at the beginning or end of a line, word, or
string. To do this you can use anchors. Two common anchors are caret (^) which represent the
start of the string, and the dollar ($) sign which represent the end of the string.
The regular expression in the following example will display only those names from the names
array which start with the letter "J" using the PHP preg_grep() function:
Example
<?php
$pattern = "/^J/";
$names = array("Jhon Carter", "Clark Kent", "John Rambo");
$matches = preg_grep($pattern, $names);
Pattern Modifiers
A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers
are placed directly after the regular expression, for example, if you want to search for a pattern in
a case-insensitive manner, you can use the i modifier, like this: /pattern/i. The following table
lists some of the most commonly used pattern modifiers.
M Changes the behavior of ^ and $ to match against a newline boundary (i.e. start
or end of each line within a multiline string), instead of a string boundary.
X Allows you to use whitespace and comments within a regular expression for
clarity.
The following example will show you how to perform a global case-insensitive search using
the i modifier and the PHP preg_match_all() function.
Example
<?php
$pattern = "/color/i";
$text = "Color red is more visible than color blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Similarly, the following example shows how to match at the beginning of every line in a multi-
line string using ^ anchor and m modifier with PHP preg_match_all() function.
Example
<?php
$pattern = "/^color/im";
$text = "Color red is more visible than \ncolor blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Word Boundaries
A word boundary character ( \b) helps you search for the words that begins and/or ends with a
pattern. For example, the regexp /\bcar/ matches the words beginning with the pattern car, and
would match cart, carrot, or cartoon, but would not match oscar.
Similarly, the regexp /car\b/ matches the words ending with the pattern car, and would match
scar, oscar, or supercar, but would not match cart. Likewise, the /\bcar\b/ matches the words
beginning and ending with the pattern car, and would match only the word car.
The following example will highlight the words beginning with car in bold:
Example
<?php
$pattern = '/\bcar\w*/';
$replacement = '<b>$0</b>';
$text = 'Words beginning with car: cart, carrot, cartoon. Words ending with car: scar, oscar,
supercar.';
echo preg_replace($pattern, $replacement, $text);
?>
References
https://www.plus2net.com/php_tutorial/variables2.php
https://www.peachpit.com/articles/article.aspx?p=674688&seqNum=7
https://www.phptutorial.net/php-tutorial/php-filter_input/
https://www.tutorialrepublic.com/php-tutorial/php-regular-expressions.php
https://www.php.net/manual/en/control-structures.switch.php
Appendix
Comparisons of $x with PHP functions
true true false true false true True false true false false true false
false false true false true false False true false true true false true
1 true false true false false True false false false false false false
0 false true false true false False true false true false false* false*
-1 true false false false true False false true false false false false
"1" true false true false false True false false false false false false
"0" false true false true false False true false false false false false
"-1" true false false false true False false true false false false false
null false true false true false False false false true true false true
[] false true false false false False false false true true false false
"php" true false false false* false False false false false false true false
"" false true false false* false False false false true false false true
true true false false false false False false false false false false false
false false true false false false False false false false false false false
1 false false true false false False false false false false false false
0 false false false true false False false false false false false false
-1 false false false false true False false false false false false false
"1" false false false false false True false false false false false false
"0" false false false false false False true false false false false false
"-1" false false false false false False false true false false false false
null false false false false false False false false true false false false
[] false false false false false False false false false true false false
"php" false false false false false False false false false false true false
"" false false false false false False false false false false false true