PHP-Chapter-4-١
PHP-Chapter-4-١
Development
ITSE 3302
تطوير تطبيقات الشبكة العالمية
Dr. Moamar Elyazgi
PHP Language
Chapter 4
PHP
Strings, Web Concepts and
GET and POST Methods
4.1 Strings
Double Quoted
You can also use double quotation marks (").
However, single and double quotation marks work in different ways.
Strings enclosed in single-quotes are treated almost literally, whereas the
strings delimited by the double quotes replaces variables with the string
representations of their values as well as specially interpreting certain escape
sequences.
6
4.1 Strings
To include a literal string in your PHP script, simply enclose the string in:
Single quotes — e.g. 'Hello there!', or
Double quotes — e.g. "Hello there!".
If you use single quotes then PHP reads the string exactly as you typed it. Double
quotes work in a similar way, but a couple of extra features also come into play:
Variable parsing: Variable names within the string are replaced with the
corresponding variable values
Character escaping: You can use escape sequences to include special characters
7
in the string
4.1 Strings
<? <!DOCTYPE html>
<html lang="en">
$variable = "name";
<head>
$literally = 'My $variable will not print!\\n'; <title>PHP Single and Double Quoted
print($literally); Strings</title>
$literally = "My $variable will print!\\n"; </head>
print($literally); <body>
<?php
?>
$my_str = 'World';
My $variable will not echo "Hello, $my_str!<br>";
print!\n echo 'Hello, $my_str!<br>';
My name will print echo '<pre>Hello\tWorld!</pre>';
echo "<pre>Hello\tWorld!</pre>";
Hello, World!
echo 'I\'ll be back';
Hello, $my_str!
Hello\tWorld!
?>
Hello World! </body>
I'll be back </html 8
4.1.1 String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
Hello World 1234
$string2="1234"; empty space
echo $string1 . " " . $string2;
?>
we used the concatenation operator two times. This is because we had to insert a
third string.
Between the two string variables we added a string with a single character, an
empty space, to separate the two variables. 9
4.1.1 More String Operator
ً
طويال ،فقد قسمناها إلى قسمين ،لنأخذ فكرة ً عن محتواهما: ول ّما كان الحديث عن السالسل النصيّة يحتاج شر ًحا
القسم األول:
.1إنشاء والوصول إلى السالسل النصية باستخدام $و {} ،واستخدام الدالة )(.strlen
.2البحث في السالسل النصية باستعمال الدوال:
strstr().1
strpos() .2و )(strrpos
substr_count().3
strpbrk().4
.3االستبدال في السالسل النصية باستخدام الدوال:
str_replace() .1
substr_replace ().2
Strtr().3
.4التعامل مع حاالت الحروف الكبيرة ( ) uppercaseوالصغيرة ) )lowercaseباستخدام الدوال:
strtolower().1
strtoupper().2
ucfirst().3
lcfirst().4
10
ucword().5
.5النسخ غير الحساسة لحالة األحرف لجميع الدوال السابقة.
4.1.1 More String Operators
القسم الثاني:
.1تنسيق السالسل النصية باستخدام )( ،printfبما في ذلك تعيين دقة األرقام العشرية.
.2إزالة الفراغات ( )trimmingمن أطراف السالسل النصية باستعمال الدوال:
trim() .1
ltrim().2
rtrim().3
<?php
echo strlen(‘Welcome to Cloudways’); 20
?> 12
4.1.3 Searching for the First Occurrence of a String
The strstr() function is a built-in function in PHP.
It searches for the first occurrence of a string inside another string and displays the
portion of the latter starting from the first occurrence of the former in the latter (before if
specified). This function is case-sensitive.
<html>
<body>
<?php Syntax
echo strstr("Hello world!","world"); strstr(string,search,before_search)
?>
</body>
</html> world!
13
4.1.3 Searching for the First Occurrence of a String
The stristr() function searches for the first occurrence of a string inside another
string.
This function is binary-safe.
This function is case-insensitive. For a case-sensitive search, use strstr() function.
<html>
<body>
<?php Syntax
echo stristr("Hello stristr(string,search,before_search)
world!","WORLD");
?>
</body> world!
</html> 14
4.1.4 Counting the number of times a substring occurs in a given string
The substr_count() is a built-in function in PHP and is used to count the number of times
a substring occurs in a given string.
The function also provides us with an option to search for the given substring in a given
range of the index.
It is case sensitive, i.e., “abc” substring is not present in the string “Abcab”.
<html>
<body>
Syntax
<?php substr_count($string, $substring, $start, $length)
echo substr_count("Hello world. The world is
nice","world");
?>
</body> 2 15
</html>
4.1.4 Counting the number of times a substring occurs in a given string
<html>
<body>
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length 12
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the 2
string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
2
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice" 1
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
0
</body>
</html>
16
4.1.5 Counting of the NUMBER OF Words in a String
Another function which enables display of the number of words in any
specific string is str_word_count(). This function is also useful in validation
of input fields.
Syntax
Str_word_count(string)
<?php
3
echo str_word_count(‘Welcome to Cloudways’);
?> 17
4.1.6 Finding Text Within a String
Strpos() enables searching particular <?php
$mystring = 'abc';
text within a string. It works simply $findme = 'a';
by matching the specific text in a $pos = strpos($mystring, $findme);
if ($pos === false) {
string. If found, then it returns the echo "The string '$findme' was not found in
the string '$mystring'";
specific position. If not found at all,
} else {
then it will return “False”. Strops() echo "The string '$findme' was found in the
string '$mystring'";
is most commonly used in echo " and exists at position $pos";
validating input fields like email. }
?>
Syntax
The string 'a' was found in the string 'abc' and exists at
18
Strpos(string,text); position 0
4.1.7 Replacing Text within a String
The str_replace() replaces all occurrences of the search text within the
replacement string.
Syntax
Str_replace(string to be replaced,text,string);
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
echo str_replace("facts", "truth", $my_str);
?>
welcome to cloudways
21
4.1.10 Comparing between Strings
Strcmp(string1,string2) — Binary safe string comparison. Note that this
comparison is case sensitive.
Syntax
Strcmp(string1,string2);
<?php
$var1 = "Hello"; $var1 is not equal to $var2 in a case sensitive string comparison
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
22
?>
4.1.11 Displaying a part of String
<?php
Displaying part of
echo substr('abcdef', 1); // bcdef
String. Through echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
substr() function you echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
can display or extract a
// Accessing single characters in a string
string from a particular // can also be achieved using "square brackets"
$string = 'abcdef';
position. echo $string[0]; // a
echo $string[3]; // d
Syntax
echo $string[strlen($string)-1]; // f
substr(string,start,length); ?>
23
4.1.12 Removing Whitespace (Trimming)
The trim() function removes whitespace and other predefined
characters from both sides of a string.
Related functions: ltrim() - Removes whitespace or other predefined
characters from the left side of a string.
rtrim() - Removes whitespace or other predefined characters from the
right side of a string.
Syntax
trim(string,charlist) 24
4.1.12 Removing Whitespace (Trimming)
<?php
$str = " Hello World! ";
echo "Without trim: " . $str; Without trim: Hello World!
With trim: Hello World!
echo "<br>";
echo "With trim: " . trim($str);
?>
<?php
$str = "\n\n\nHello World!\n\n\n";
echo "Without trim: " . $str; Without trim: Hello World!
echo "<br>"; With trim: Hello World!
echo "With trim: " . trim($str);
?> 25
4.1.13 Padding a String to a New Length
The str_pad() function is used to pad a string to a new length. It
returns the padded string.
Syntax
str_pad(str, len, pad_str, pad_type)
Parameters
str − The string to pad
len − The new string length
pad_str − The string to use for padding
pad_type − The side to pad the string.
26
4.1.13 Padding a String to a New Length
The following are the possible values −
STR_PAD_BOTH − Pad to both sides of the string. If not an even
number, the right side gets the extra padding
STR_PAD_LEFT − Pad to the left side of the string
STR_PAD_RIGHT − Pad to the right side of the string.
Return
The str_pad() function returns the padded string.
27
4.1.13 Padding a String to a New Length
<?php
$s = "Welcome"; $$$Welcome
echo str_pad($s,10,"$",STR_PAD_LEFT);
?>
<?php
$s = "Welcome"; Welcome$$$
echo str_pad($s,10,"$",STR_PAD_RIGHT);
?>
<?php
$s = "Welcome"; $Welcome$$
echo str_pad($s,10,"$",STR_PAD_BOTH);
?>
28
4.2 Web Concepts and PHP Form Handling
If you are already familiar with the terms TCP/IP, HTTP, Web servers, Web
clients, HTML, URL, Intranet, and Internet, and you know how information is
stored and transmitted over the Web, you don't need to read this section.
Storing, locating, and transmitting information on the Web
29
4.2 Web Concepts and PHP Form Handling
This section demonstrated how the client browser can be redirected.
One of the most powerful features of PHP is the way it handles HTML forms.
The basic concept that is important to understand is that any form element will
automatically be available to your PHP scripts.
There is nothing special about this form. It is a straight HTML form with no special tags
of any kind. When the user fills in this form and hits the submit button.
Form data is submitted to the PHP file for processing using POST here.
Other methods you may use instead of POST is GET and REQUEST.
In a moment we will see differences between those three methods 30
4.2.1 GET vs POST vs REQUEST
Both GET, POST and REQUEST are treated as $_GET, $_POST and $_REQUEST.
All of these are superglobals, i.e. automatically global variables. So, they can be accessed
throughout a script, including within functions or methods, without declaring them explicitly as
global $variable;.
$_GET is an associative array of variables passed to the current script via the URL parameters.
$_POST is an associative array of variables passed to the current script via the HTTP POST
method.
$_REQUEST is also an associative array. Since it contains the contents of $_GET.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
31
<?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"; 37
4.2.6 Example B: Complete Form - 2
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
38
4.2.6 Example B: Complete Form - 3
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows
dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
} 39
4.2.6 Example B: Complete Form - 4
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
40
4.2.6 Example B: Complete Form - 5
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
>
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></te
xtarea>
<br><br>
41
4.2.6 Example B: Complete Form - 6
Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="other") echo "checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email; 42
4.2.6 Example B: Complete Form - 7
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>"; In example B, to show the values in the input fields after the user hits
echo $gender; the submit button, we add a little PHP script inside the value attribute
?> of the following input fields: name, email, and website. In the
comment textarea field, we put the script between the <textarea> and
</body>
</textarea> tags. The little script outputs the value of the $name,
</html>
$email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For
this, we must manipulate the checked attribute (not the value attribute
for radio buttons):
43
44