Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WEB TECHNOLOGY-1 chp 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

CHAPTER

2
Function and String
Objectives…
To understand Basic Concepts of Function and String in PHP
To learn Function Declaration, Types, Definition, Arguments etc.
To learn Basic Concepts of Strings like Declaration, String Functions, etc.

2.0 INTRODUCTION
• A function in PHP is a block of statements that can be used repeatedly in a program. A
string in PHP is a collection of characters.
• A function in PHP is a reusable block of code that performs a specific action or task. It
takes input from the user in the form of parameters, performs certain actions, and
gives the output.
• Functions can either return values when called or can simply perform an operation
without returning any value.

2.1 OVERVIEW OF FUNCTION


• A function is a named block of code that is defined to perform a specific task, possibly
acting upon a set of values given to it, or parameters and may or may not return a
value.
• A function can be called from another part of the program. The code inside a function
is not executed until the function is called.
• There are two types of functions i.e. built-in function and user defined functions.
1. Built-in Functions are also called as pre-defined functions that perform a wide
range of operations. PHP is very rich in terms of Built-in functions.
2. User Defined Functions are defined by user as per their need or requirements.
• Functions are useful because they contribute to rapid, reliable, error-reducing coding.
A function can be called many times in a page but it is compiled only once.
• As a function is written only once and removes the need to write the codes for the
same task every time it requires, it reduces number of bugs and saves time for
programming.
• As functions separate codes that perform a specific task, it improves readability.

2.1
Web Technologies - I Function and String

Advantage of PHP Functions:


1. Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
2. Less Code: It saves a lot of code because you don't need to write the logic many
times. By the use of function, you can write the logic only once and reuse it.
3. Easy to Understand: PHP functions separate the programming logic. So it is easier
to understand the flow of the program because the program logic is divided in the
form of functions.
4. Better Code Organization: PHP functions allow us to group blocks of related code
that perform a specific task together.

2.1.1 Defining a Function


• A function is a self-contained block of code that performs a specific task. To define a
function In PHP following syntax is used:
function [&] function_name([parameter[,...]])
{
//Code to be executed…
}
• A function definition starts with the keyword ‘function’ followed by the name of
function with parentheses (). The [&] is optional and if it is used then the function
returns reference.
• A function name can be any string that begins with a alphabet letter or underscore ( _).
All the PHP code in function should be put inside curly brackets (braces { }) containing
the code to be executed each time that function gets called.
• Function names are case-insensitive. It means count(), Count() and COUNT() refer to
the same function. By convention, PHP built-in functions are in lowercase.
Example for function:
<?php
/* Defining a PHP Function */
function writeMsg()
{
echo "Hello PHP";
}
/* Calling a PHP Function */
writeMsg();
?>
Output:
Hello PHP
2.2
Web Technologies - I Function and String

2.1.2 Calling a Function


• Calling a function is simple – just write the name of the function followed by a pair of
parentheses.
• We can call a function in PHP by using the following syntax:
$some_value=function_name([parameter, ...]);
• After calling a function, the code/statements inside it are executed. After the function
execution is completed, the program control returns to the point where the function
was called.
• Fig. 2.1 shows how caller and receiver functions work together.

Fig. 2.1: How Caller and Receiver Functions Work Together

For example:
<?php
function welcome()
{
echo “Hi, welcome to Schools of Web.”;
}
welcome(); // Function welcome() is called here.
?>
Output:
Hi, welcome to Schools of Web.
• Explanation of above Program: The function welcome() is defined. In this stage
nothing happens. When the function is called, the interpreter finds it and enters into
it, executes the statement(s) inside it. Here it prints the sentence “Hi, welcome to
Schools of Web.”.
2.1.3 Function Parameters [Oct. 18, April 19]
• Information can be passed to functions through arguments. Arguments (or
parameters) are specified after the function name, inside the parentheses ().
• If a function accepts more than one parameter, each parameter has to be separated by
a comma (,). The arguments are evaluated from left to right.
2.3
Web Technologies - I Function and String

For example:
function strcat($left, $right)
{
$combined_string = $left . $right;
echo $combined_string;
}
• PHP supports passing arguments by value (the default), passing by reference, and
default argument values. Variable-length argument lists are also supported.
• By default, function arguments are passed by value (so that if the value of the
argument within the function is changed, it does not get changed outside of the
function).
• To allow a function to modify its arguments, they must be passed by reference. When
a function argument is passed by reference, changes to the argument also change the
variable that was passed in.
• We can pass an argument by reference by adding an ampersand (&) to the variable
name in either the function call or the function definition.
For example:
<?php
function doubler(&$value)
{
$value = $value * 2;
}
$a = 3;
doubler($a);
echo $a; // Outputs 6
?>

2.1.4 Returning Values


• A function can return a value using the return statement. Any type may be returned,
including arrays and objects.
• When PHP encounters the return statement, it terminates the function immediately
and returns the value back.
For example:
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs 16
?>
2.4
Web Technologies - I Function and String

• A function cannot return multiple values, but similar results can be obtained by
returning an array.
<?php
function day_name()
{
$day1 = ”Monday”;
$day2 = ”Tuesday”;
$day3 = ”Wednesday”;
return array($day1, $day2, $day3);
}
$days = day_name();
echo $days[0] . ” ” . $days[1] . ” ” . $days[2];
?>
Output:
Monday Tuesday Wednesday
• Function day_name() creates an array that has three elements in it and returns to its
caller.
• When the function is called, the function returns the array to the caller assigns it in
the $days variable. The next line prints the values of the array elements.

2.1.5 Function Body


• The code inside the curly braces { } is a function body. We can put PHP code, HTML
code or mixed PHP and HTML code inside the body.
• For example, the following function displays the header of a web page:
function display_header($header)
{
echo “<h1>” . $header . “</h1>”;
}

2.2 DEFAULT PARAMETERS


• We can specify a default argument value in function. While calling PHP function, if we
do not specify any argument, it will take the default argument.
• PHP function allows us to pass default values to its parameters. To specify a default
value for a parameter, we assign the parameter a scalar value in the function
declaration.
2.5
Web Technologies - I Function and String

Example:
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
• The default value must be a constant expression, not (for example) a variable, a class
member or a function calls.
• Note that when using default arguments, any defaults should be on the right side of
any non-default arguments; otherwise, things will not work as expected.

2.3 VARIABLE PARAMETERS


• A function may require a variable number of arguments. A function may require a
variable number of arguments instead of having fixed number of arguments.
• PHP has support for variable-length argument lists in user-defined functions. This is
implemented using the "..." token in PHP 5.6 and later versions and using the
func_num_args(), func_get_arg(), and func_get_args() functions in earlier versions.
• To declare a function with a variable number of arguments, keep parameter block
completely empty.
function xyz()
{
// some code …
}
• In PHP following are the three functions are available to retrieve the parameters
passed to it:
1. func_get_args() returns an array containing all parameters passed to the function.
[April 18]
2.6
Web Technologies - I Function and String

2. func_num_args() returns the number of parameters provided to the function.


[Oct. 17]
3. func_get_args() returns specific arguments from the parameters.
Example for displaying the sum of all the parameter:
<?php
function sum()
{
$count = 0;
for($i = 0; $i < func_num_args( ); $i++)
{
$count += func_get_arg($i);
}
return $count;
}
echo sum(1, 2, 3, 4);
echo sum(1, 4);
echo sum();
echo sum(10, 20, 30);
?>
Output:
10
5
0
60

2.4 MISSING PARAMETERS [April 17, Oct. 17]

• We can pass any number of arguments to the function. If we do not pass any value to
the parameter, the parameter remains unset and a warning is displayed for each of
them.
Example:
<?php
function xyz($a, $b, $c)
{
if (isset ($a))
echo “a is set <br>”;
2.7
Web Technologies - I Function and String

if (isset ($b))
echo “$b is set <br>”;
if (isset ($c))
echo “c is set <br>”;
}
echo “with 3 arguments <br>”;
xyz(1, 2, 3);
echo “with 2 arguments<br>”;
xyz(1, 2);
echo “with 1 argument<br>”;
xyz(1);
?>
Output:
with 3 arguments
1 is set
2 is set
3 is set
with 2 arguments
1 is set
2 is set
Warning: Missing argument 3 for xyz()
with 1 argument.
1 is set.
Warning: Missing argument 2 for xyz()
Warning: Missing argument 3 for xyz()
• In above program:
1. To check if parameter is missing or not, we can use built in function isset().
2. The isset() functions returns true if the value is set to the argument passed to it,
otherwise it returns result as false. [April 16]

2.5 VARIABLE FUNCTION AND ANONYMOUS FUNCTION


• If name of a variable has parentheses (with or without parameters in it) in front of it,
PHP parser tries to find a function whose name corresponds to value of the variable
and executes it. Such a function is called variable function.
• The variable function feature of PHP is useful in implementing callbacks, function
tables etc.
• Anonymous function is a function without any user defined name. Such a function is
also called closure or lambda function.
2.8
Web Technologies - I Function and String

2.5.1 Variable Function [April 17, Oct. 17]

• PHP supports the concept of variable functions. This means that we can call function
based on value of a variable.
• If a variable name has round parentheses appended to it, PHP will look for a function
with the same name as whatever the variable evaluates to, and will attempt to execute
it.
• The variable function does not work with echo(), print(), unset(), isset() language
constructs.
• PHP allows us to store a name of a function in a string variable and use the variable to
call the function. Variable functions are useful in cases that we want to execute
functions dynamically at run-time.
• The following example demonstrates how to use variable functions:
<?php
function find_max($a,$b)
{
return $a > $b? $a: $b;
}
function find_min($a,$b)
{
return $a < $b? $a: $b;
}
$f = 'find_max';
echo $f(10,20); // Outputs 20
$f = 'find_min';
echo $f(10,20); // Outputs 10
?>
• First, we defined two functions namely, find_min() and find_max() . Then, we called
those function based on the value of string variable $f.
• Notice that we need to put parentheses after the variable in order to call the function
specified by the value of the variable.
2.5.2 Anonymous Function [Oct. 17, 18, April 18]
• In PHP we can define a function that has no specified name called as an anonymous
function or a closure.
• An anonymous function also called as lambda function. We often use anonymous
functions as values of callback parameters.
• The anonymous function is created using the create_function(). It takes following two
parameters:
o First parameter is the parameter list for anonymous functions
o Second parameter contains the actual code of the function. The function name is
randomly generated and returned.
2.9
Web Technologies - I Function and String

• The syntax for anonymous function (or lambda function) using reate_function():
$f_name = create_function(args_string, code_string);
For example:
<?php
$add = create_function('$a,$b', 'return($a+$b);');
$r = $add(2,3);
echo $r;
?>
Output:
5

2.6 TYPES OF STRINGS IN PHP [April 16, 17, 18, Oct. 16, 18]
• PHP string is a sequence of characters and used to store and manipulate text.
• A “string” of text can be stored in a variable in much the same way as a numeric value
but the assignment must surround the string with quote marks (“…” or ‘….’) to denote
its beginning and end like "Hello world!" or ‘Hello world!’.
• Strings are very useful to store names, passwords, address, and credit-card number
and so on. For that reason, PHP has large number of functions for working with
strings.
• There are three different ways to write string in PHP as explained below:
1. Single-Quoted String:
• In this method, string is enclosed with single quotation mark (‘…’). It is the easiest way
to specify string in PHP.
For Example: ‘Hello PHP’ ‘Computer Basics’ ‘Pune’ etc.
• The limitation of single-quoted string is that variables are not interpolated.
For example:
<?php
$name = ‘Amar;
$str = ‘Hello $name’; // Single-quoted string
echo $str;
?>
Output:
Hello $name
• In the above output the value of variable $name is not printed.
2. Double-Quoted String:
• It is the most commonly used quote to express string. In this method, characters are
enclosed with double quotation marks (“…”).
• PHP interpreter interprets variables and special characters inside double quotes.
2.10
Web Technologies - I Function and String

• In the following example, the above example is re-written using double quotes.

For example:
<?php
$name = ‘PHP’;
$str = “Hello $name”; // Double-quoted string
echo $str;
?>
Output:
Hello PHP
3. Here Documents:
• Single-quoted and double-quoted strings allow string in single line. To write multiline
string into a program heredoc is used.
Rules of using heredoc Syntax:
(i) Heredoc syntax begins with three less than signs (<<<) followed by identifier
(a user defined name). The identifier can be any combination of letters, numbers,
underscores but the first character must be a letter or an underscore.
(ii) The string begins in the next line and goes as long as it requires.
(iii) After the string, the same identifier that is defined after the (<<<) signs in the first
line should be placed at the end. Nothing can be added in this last line except a
semicolon after the identifier and it is optional.
(iv) Space before and after <<< is essential.
Syntax:
$var_name = <<< identifier
// String statement
// String statements
identifier;
For example:
<?php
$str = <<< EOD
PHP is suited for web development and can be embedded into HTML.\n
PHP is server-side scripting language
EOD;
echo $str;
?>
Output:
PHP is suited for web development and can be embedded into HTML. PHP is
server-side scripting language.
4. Nowdoc syntax:
• If heredoc syntax works similar to double quote, then nowdoc syntax works similar to
single quote.
• Like single quote, no variable inside the nowdoc is interpreted.

2.11
Web Technologies - I Function and String

Rules of using nowdoc Syntax:


(i) Nowdoc supports all the syntax rules of heredoc except the starting name.
(ii) It must be enclosed by single quotes.
For example:
<?php
$a = 5;
$str = <<<’EOD’
PHP is suited for web development and
can be embedded into HTML $a.\n
PHP is server-side scripting language.
EOD;
echo $str;
?>
Output:
PHP is suited for web development and can be embedded into HTML $a.
\nPHP is server-side scripting language.
• Single and double quotes in heredoc are passed through.
<?php
$a = <<< END
“It’s not going to happen!”
END;
echo $a;
?>
Output:
“It’s not going to happen!”
The new line before the trailing terminator is removed.
Variable Interpolation: [Oct. 16, 17, April 19]
• Interpolation is the process of replacing variable names in the string with the values of
those variables.
• Single quoted strings do not interpolate variables. When variable is included inside
double quoted string or heredoc string, the variable is interpreted (or parsed).
• There are following two ways to interpolate variables into strings:
1. Simple Syntax:
• In this way, the variable name is simply put inside the double-quoted string or
heredoc.
For example:
<?php
$a = ’Hello’;
$b = ’Nirali Prakashan’;
echo “$a $b”;
?>
Output:
Hello Nirali Prakashan
2.12
Web Technologies - I Function and String

2. Complex Syntax:
• In this way, variable is wrapped with { and }.
For example:
<?php
$a=1;
echo “You are the {$a}st employee”;
?>
Output:
You are the 1st employee.
• Without { } the PHP parser consider $ast as a variable and displays Noticed undefined
variable: $ast on line 3.
Character Escaping:
• Escape sequences are used for escaping a character during the string parsing. In PHP,
an escape sequence starts with a backslash \ followed by the character which may be
an alphanumeric or a special character.
• A single-quoted string only uses the escape sequences for a single quote (‘…’). All the
escape sequences like \r or \n, will be output as specified instead of having any special
meaning.
• Single quotes are used in the special case is that if we to display a literal single-quote,
escape it with a backslash (\) and if we want to display a backslash, we can escape it
with another backslash (\\).
• Escape sequences also apply to double-quoted strings. Escape sequences for double-
quoted strings are given below:
Escape Sequence Character Represented
\″ double quotes
\n newline
\r carriage return
\t tab
\\ Backslash
\$ Dollar sign
\{ left brace
\} right brace
\[ left square bracket
\] right square bracket
\o through \777 ASCII character represented by octal value.
\xo through \XFF ASCII character represented by hex value.
2.13
Web Technologies - I Function and String

2.7 PRINTING FUNCTIONS


• In PHP there are various methods to print data. There are following ways to send
output to the browser:
1. echo construct : Print many values at once.
2. print() : Prints only one value.
3. printf() : Builds a formatted string.
4. print_r() : Prints the contents of arrays, objects, and other things, in a
more-or-less human-readable form. [Oct. 17]
5. var_dump() : Prints the content of arrays, objects and other things in more
human readable form alongwith size, type, length of elements
useful for debugging. [Oct. 17]
• Let us see above functions in detail.
1. echo Construct: [April 18]
• The echo is not a PHP function it a construct. The echo construct puts string into HTML
of a PHP-generated page then it send to the browser.
• The echo construct looks like a function but it is a language constraints. This means
that we can omit the parentheses, so the following are equivalent:
echo "Printy";
echo("Printy"); // also valid
• We can specify multiple items to print by separating them with commas:
echo "First", "second", "third";
Output:
First Second Third
• It is a parse error to use parentheses when trying to echo multiple values:
// this is a parse error
echo("Hello", "world"); //invalid
• Because echo is not a true function, we can’t use it as part of a larger expression:
// parse error
if (echo("test")) { //invalid
echo("it worked!");
}
• Such errors are easily remedied, though, by using the print() or printf() functions.
2. print() Function: [April 18]
• The print() function sends one value (its argument) to the browser. It returns true if
the string was successfully displayed and false otherwise.
2.14
Web Technologies - I Function and String

For example:
if(! print("Hello, world"))
{
die("you're not listening to me!");
}
Output:
Hello, world
3. printf() Function:
• The printf() function outputs a formatted string. The first argument to printf() is the
format string. The remaining arguments are the values to be substituted in.
Format Modifiers:
• Each substitution marker in the template consists of a % sign, followed by modifiers
and ends with a type specifier.
• Following sequence of modifiers is necessary.
(i) A padding specifier denoting the character to use to pad the result to the
appropriate string size. Padding with spaces is the default.
(ii) A sign minus (−) forces the string to be left justified. Default is right justified.
(iii) The minimum length of the element. If the result is less than this number of
characters, then padded with some value.
(iv) For floating point numbers, it gives or dictates how many decimal digits will be
displayed.
Type Specifiers:
• The type specifier tells printf() what type of data is being substituted. There are
different types as shown below:
Specifier Meaning
B The argument is integer and is displayed as a binary number.
C The argument is integer and is displayed as a character with that
value.
d or I The argument is integer and is displayed as a decimal number.
e, E or f Argument is double, displayed as a floating point number.
g or G Argument is double with precision, displayed as floating point
number.
O Argument is integer and displayed as a floating point number.
S Argument is string and displayed as such.
U Argument is an unsigned integer and is displayed as decimal.
x Argument is integer, displayed in hexadecimal with lowercase letters
X Argument is an integer and displayed as a hexadecimal with
uppercase letter.

2.15
Web Technologies - I Function and String

Some examples:
printf(‘%2f’, 27.452);
Output: 27.45
printf('The hex value of %d is %x', 214, 214);
Output: The hex value of 214 is d6
printf('Bond. James Bond. %03d.', 7);
Output: Bond. James Bond. 007.
$month = 2; $day = 15; $year = 2002;
printf('%02d/%02d/%04d', $month, $day, $year);
Output: 02/15/2002
printf('%.2f%% Complete', 2.1);
Output: 2.10% Complete
printf('You\'ve spent $%5.2f so far', 4.1);
Output: You've spent $ 4.10 so far
4. print_r() Function:
• The print_r() is useful for debugging purpose. It prints the contents of array, objects
and other things in more or less human-readable form.
For example:
$a = array('name' => 'Amar', 'age' => 35);
print_r($a);
Output:
Array
(
[name] => Amar
[age] => 35
)
5. var_dump() Function:
• The var_dump() function is used to display structured information (type and value)
about one or more variables.
For example:
<?php
var_dump(14) . “<br>”; // <br> is used for line change
var_dump(“Hello”) . “<br>”;
var_dump(25, “ty1”);
?>
2.16
Web Technologies - I Function and String

Output:
Int(14)
String(5) “Hello”
Int(25)string(3) “ty1”
• Boolean values and NULL are not meaningfully displayed by print_r().
For example:
print_r(true); // Outputs 1
print_r(false); // Nothing is displayed
print_r(null); // Nothing is displayed
• For this reason, var_dump() is preferable to print_r() for debugging. The var_dump()
function displays any PHP value in more human-readable format.
For example:
var_dump(true);
Output: bool(true)
var_dump(false);
Output: bool(false);
var_dump(null);
Output: bool(null);
var_dump(array('name' => Amar, 'age' => 35));
Output:
array(2)
{
["name"]=>string(4) "Amar"
["age"]=>int(35)
}
• In recursive structures, print_r() loops infinitely while var_dump() cuts off after
visiting the same element three times.
Accessing Individual Characters:
• We can access the individual character of a string using [].
For example:
<?php
$str = "Hello";
echo $str[0]; // H
?>
2.17
Web Technologies - I Function and String

• The strlen() function returns the number of characters in a string.


<?php
$str = "Hello";
for ($i=0; $i < strlen($str); $i++)
{
printf("The %dth character is %s\n", $i, $str[$i]);
}
?>
Output:
st
The 0th character is H The 1 character is e. The 2th character is l.
rd
The 3 character is l. The 4th character is o
Cleaning String:
• Two common problems with raw data often we get from user or files are the presence
of extra white spaces and incorrect capitalization (uppercase versus lowercase).
• To recover from these problems, the data needs to be cleaned up before use.
Removing Whitespace:
• We can remove leading or trailing whitespace with the trim(), ltrim() and rtrim()
functions explained below:
1. trim(): Returns the string with whitespaces removed from the beginning and from
the end. [April 19]
Syntax: trim(string [, charlist ]);
2. ltrim(): It removes white spaces only from the start. Here ‘l’ indicates ‘left’.
Syntax: ltrim(string [, charlist ]);
3. rtrim(): It removes whitespaces only from the end. Here r indicates ‘right’.
Syntax: rtrim(string [, charlist ]);
• Apart from the whitespaces following default characters are removed.
Character Meaning
“” space
“\t” tab
“\n” newline
“\r” carriage return
“\o” null byte
“\XOB” vertical tab
• The charlist is optional string parameter which specifies the characters apart from
default characters to be trimed (removed) from the string.
For example:
$title = " Programming PHP \n";
$str_1 = ltrim($title); // $str_1 is "Programming PHP \n"
$str_2 = rtrim($title); // $str_2 is " Programming PHP"
$str_3 = trim($title); // $str_3 is "Programming PHP"
2.18
Web Technologies - I Function and String

Changing Case:
• PHP has several functions for changing the case of strings. Each function takes a string
as an argument and returns a copy of that string, appropriately changed.
• PHP has following functions for changing the case of strings:
1. strtolower() and strtoupper() operate on entire string.
2. ucfirst() operates only on first character of the string.
3. ucwords() operates on first character of each word of the string. [April 19]
For example:
$S1 = strtolower (“Hello World”); // $S1 = “hello world”
$S2 = strtoupper (“Hello World”); // $S2 = “hello WORLD”
$S3 = ucfirst (“hello world”); // $S3 = “Hello world”
$S4 = ucwords (“hello world”); // $S4 = “Hello World”

2.8 ENCODING AND ESCAPING


• PHP programs often interact with HTML pages, web addresses (URLs) and databases.
There are functions to help us to work with those types of data.
• HTML web page addresses, and database commands are all strings, but they each
require different characters to be escaped in different ways.
• For instance, a space in a web address must be written as %20, while a literal less-than
sign (<) in an HTML document must be written as &lt;.
• PHP has a number of built-in functions to convert to and from these encodings.
1. HTML:
• Special characters in HTML are represented by entities such as &amp; and &lt;. There
are two functions to convert special characters in a string into their entities.
(i) htmlentities() Function:
• The htmlentities() function converts all applicable characters to HTML entities.
Syntax: string htmlentities(string str[, int quote_style][, String charset])
For example:
<?php
$str = htmlentities(“Hello World <p>”);
echo $str;
?>
Output in Terminal:
Hello World &lt;p&gt;
Output in Browser:
Hello World <p>
• Second optional parameter contains the following value:
ENT_COMPAT : Default. converts only double quotes
ENT_QUOTES : Converts double and single quotes
ENT_NOQUOTES : Does not convert any quotes
2.19
Web Technologies - I Function and String

For example:
$input = <<< end
"Programming PHP" by Nirali
end;
echo htmlentities($input);
// &quot;Programming PHP&quot; by Nirali
echo htmlentities($input, ENT_QUOTES);
// &quot;Programming PHP&quot; by O&#039;Nirali
echo htmlentities($input, ENT_NOQUOTES);
// “Programming PHP” by Nirali
• Charset is optional. It is a string that specifies which character-set to use. The default is
UTF-8.
(ii) htmlspecialchars() Function:
• The htmlspecialchars() function converts special characters to HTML entities.
• Certain characters have special significance in HTML, and should be represented by
HTML entities if they are to preserve their meanings. This function returns a string
with these conversions made.
• If we require all input substrings that have associated named entities to be translated,
use htmlentities() instead.
• The translations performed are:
o & (ampersand) becomes &amp;
o " (double quote) becomes &quot;
o ' (single quote) becomes &#039;
o < (less than) becomes &lt;
o > (greater than) becomes &gt;
• If we have an application that displays data that a user has entered in a form, we need
to run that data through htmlspecialchars( ) before displaying or saving it.
• For example, if user enters a string like "angle < 30", the browser will think the special
characters are HTML, and we will have a garbled page.
Syntax:
string htmlspecialchars(string str[, int quote_style][, String charset])
• The syntax and meaning of quote_style and charset are same as htmlentities().
For example:
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>
2.20
Web Technologies - I Function and String

(iii) Removing HTML Tags:


• The strip_tags() function removes HTML tags from a string.
Syntax: strip_tags(string, allow);
• First parameter is input string, second parameter is optional which specifies allowable
tags will not be removed.
Example:
$input = "Programming <b><i>PHP</i></b>";
echo $input;
// Programming PHP displays the string PHP in bold and italic
echo strip_tags($input);
// Programming PHP both the tags i.e. <b> and <i> removed
echo strip_tags($input, “<b>”);
// Programming PHP
allow <b> tag to be used, all other tag will be removed
2. SQL:
• In database queries we use single quotes or double quotes with some string literals.
For example, name or some varchar type of data must be quoted with single quote.
• When we use such type of SQL queries as a string, that will be evaluated by PHP, so it
is required to escape single quote, double quote, NULL bytes and backslashes by using
backslash present in the query.
• In PHP addslashes() function adds the slashes and stripslashes() function removes
them.
For example:
<?php
$input = "SELECT * FROM customer WHERE name = 'Amar';";
$output = addslashes($input);
echo $output. "<br>";
echo stripslashes($output);
?>
Output:
SELECT * FROM customer WHERE name = \'Amar\';
SELECT * FROM customer WHERE name = 'Amar';

2.9 COMPARING STRINGS


• PHP has different operators and functions for comparing strings to each other.
2.9.1 Exact Comparisons
• When comparing values in PHP for equality we can use either the == operator or the
=== operator.
• The == (Equal) operator just checks to see if the left and right values are equal. But, the
=== (identical) operator (note the extra “=”) actually checks to see if the left and right
values are equal, and also checks to see if they are of the same variable type (like
whether they are both booleans, ints, etc.).
2.21
Web Technologies - I Function and String

• The == operator casts non-string operands to strings,


$a=5;
$b=”5”;
if($a==$b) // Output is true
• The === operator does not cast, and returns false in above case.
For example:
$a=5;
$b=”5”;
$c=5;
if(($a===$b)
{ // returns false
echo ………
}
if($a===$c) { // returns true
echo…
}
• The comparison operators (<, <=, >, >=) also work on strings. Here these operator
considers alphabetical sequence for result.
For example:
<?php
$a=”a”;
$b=”b”;
if($a<$b)
{
print” $a comes before $b”;
}
else
print” $b comes before $a”;
?>
Output:
a comes before b
• The functions strcmp() and strcasecmp() are also used for string comparison.
For example:
$result=strcmp ($S1, $S2);
Here, function returns a number less than 0 if $S1 sorts before $S2, greater than 0 if
$S2 sorts before $S1 or 0 if they are same.
• Whereas strcasecmp() converts strings to lowercase before comparing them. It means
it is case insensitive.
2.22
Web Technologies - I Function and String

2.9.2 Approximate Equality


• An approximation is anything that is similar but not exactly equal to something else.
PHP provides several functions which tests that whether two strings are
approximately equal. The functions are soundex(), metaphone(), similar_text(),
levenshtein().
• The soundex() and metaphone() functions compares the pronunciations of both
strings. If pronunciation is same then strings are same otherwise not. [Oct. 17]
• The metaphone() function is generally more accurate. The soundex() function
calculates the soundex key of a string.
Syntax: soundex(string)
For example:
$a=”Fred”;
$b=”Phred”;
if(soundex($a)==soundex($b))
{
print”soundex: sounds same”;
}
else
{
print “soundex: doesn’t sound same”;
}
Output:
soundex: doesn’t sound same.
• The metaphone() function calculates the metaphone key of a string.
Syntax: metaphone(string,length)
For example:
$a=”Fred”;
$b=”Phred”;
if(metaphone($a)==metaphone($b))
{
print“metaphone: sounds same”;
}
else
{
print”metaphone: doesn’t sounds same”;
}
Output:
metaphone: sounds same
2.23
Web Technologies - I Function and String

• The similar_text() function calculates the similarity between two strings in percent. It
returns the number of characters that its two string arguments have in common.
[April 18]
Syntax: int similar_text (string $first, string $second [, float &$percent])
• First and second parameter contains first and second string. Third optional parameter
specifies a variable name for storing the similarity in percent.
• The similar_text() function returns the number of characters that its two string
arguments have in common. Hence, third parameter stores the value in percentage.
For example:
<?php
$s1="There";
$s2="Their";
$c=similar_text($s1, $s2, $p);
printf("%d characters in common. Strings are %f percent same", $c, $p);
?>
Output:
4 characters in common. Strings are 80.000000 percent same
• Then levenshtein() function gives how many characters you must add, substitute, or
remove to make them the same.
• The levenshtein() function returns the Levenshtein distance between two strings.
• The Levenshtein distance is the number of characters we have to replace, insert or
delete to transform string1 into string2.
Syntax: int levenshtein(string $str1, string $str2)
For example:
$similarity = levenshtein(“cat”, “cot”);
// $similarity is 1

2.10 MANIPULATING AND SEARCHING STRINGS [April 18]


• In PHP, there are many functions for modification and searching of string. Some
common functions are explained in this section.
1. substr() Function: [April 17, Oct. 17]
• The substr() function returns a part (substring) of a string.
Syntax: string substr (string $string, int $start [, int $length])
• This function returns the portion of string specified by the start and length
parameters.
nd
• Here 2 argument ‘start’ means position in string at which to begin copying. The
length argument is the number of character to copy (default is upto end of string).
2.24
Web Technologies - I Function and String

For example:
<?php
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
?>
2. substr_replace() Function:
• This function replaces text within a portion of a string.
Syntax: string substr_replace (string $original, string $replacement,
int $start [, int $length])
• The function replaces the part of ‘original’ indicated by the ‘start’ (0 means the start of
the string) and ‘length’ values with the string ‘replacement’.
• If no fourth argument is given, substr_replace( ) removes the text from ‘start’ to the
end of the string.
For example:
<?php
$greeting = "good morning Nirali";
$farewell = substr_replace($greeting, "bye", 5, 7);
echo $farewell;
?>
Output:
good bye Nirali
3. substr_count() Function:
• This function count the number of substring occurrences.
Syntax:
int substr_count(string $big_str, string $small_str
[, int $offset = 0 [int $length]])
• Returns the number of times the small_str substring occurs in the big_str string. Please
note that small_str is case sensitive. ‘offset’ is from where to start counting.
For example:
<?php
$n = 'This is a test';
echo substr_count($n, 'is'); // 2
?>
2.25
Web Technologies - I Function and String

4. substr_compare() Function:
• Comparison of two strings from an offset, up to length characters.
Syntax:
int substr_compare(string $main_str, string $str, int $offset
[, int $length[, bool $case_insensitivity = false ]])
• The substr_compare() compares ‘main_str’ from position ‘offset’ with ’str’ upto ‘length’
characters.
• Returns < 0 if ‘main_str’ from position ‘offset’ is less than ‘str’, > 0 if it is greater than
‘str’, and 0 if they are equal.
For example:
<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>
5. strrev() Function: [April 18]
• This function takes a string and returns a reversed copy of it.
Syntax: string strrev(string $string)
For example:
<?php
echo strrev("Hello World!");
?>
Output:
!dlroW olleH

6. str_repeat() Function:
• This function takes a string and count and after it, repeats the string that many times.
Syntax: string str_repeat(string $input , int $multiplier)
Returns ‘input’ repeated ‘multiplier’ times.
2.26
Web Technologies - I Function and String

For example:
<?php
$string = "Hello ";
$x = 5;
$result = str_repeat($string, $x);
echo $result;
?>
Output:
Hello Hello Hello Hello Hello
7. str_pad() Function: [April 19]
• The str_pad() function pads a string to a new length.
Syntax:
string str_pad (string $input , int $pad_length
[, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT]])
• This function returns the ‘input’ string padded on the left, the right, or both sides to the
specified padding length.
• If the optional argument ‘pad_string’ is not supplied, the ‘input’ is padded with spaces,
otherwise it is padded with characters from ‘pad_string’ up to the limit.
• Optional argument ‘pad_type’ can be STR_PAD_RIGHT, STR_PAD_LEFT, or
STR_PAD_BOTH. If ‘pad_type’ is not specified it is assumed to be STR_PAD_RIGHT.
For example:
<?php
$input = "PHP";
echo str_pad($input, 10); // "PHP "
echo str_pad($input, 10, "=", STR_PAD_LEFT); // "=======PHP"
echo str_pad($input, 10, "=", STR_PAD_BOTH); // "===PHP===="
echo str_pad($input, 10 , "="); // "PHP======="
?>

2.10.1 Decomposing a String [April 16]

• PHP provides several functions to break a string into smaller components. These
functions are explode(), implode(), strtok() and sscanf().
1. explode() Function: [April 19]
• It breaks a string into smaller parts and stores it in an array.
Syntax: array explode (string $delimiter, string $str [, int $limit])
2.27
Web Technologies - I Function and String

• Returns an array of strings, each of which is a substring of ‘str’ formed by splitting it


on boundaries formed by the string ‘delimiter’.
• If ‘limit’ is set and positive, the returned array will contain a maximum of ‘limit’
elements with the last element containing the rest of ‘str’.
• If the ‘limit’ parameter is negative, all components except the last –‘limit’ are returned.
• If the ‘limit’ parameter is zero, then this is treated as 1.
For example:
<?php
$str = 'one|two|three|four';
$arr = explode('|', $str);
print_r($arr);
echo "<br>";
$arr = explode('|', $str, 2);
print_r($arr);
echo "<br>";
$arr = explode('|', $str, -1);
print_r($arr);
?>
Output:
Array ( [0] => one [1] => two [2] => three [3] => four )
Array ( [0] => one [1] => two|three|four )
Array ( [0] => one [1] => two [2] => three )
• Since, in the second case the limit is two, hence the string will be divided into two
parts. In the third case since the limit is negative so except the component ‘four’,
remaining components will be returned.
2. implode() Function: [April 19]
• It creates a string from an array of smaller strings.
Syntax: string implode (string $glue, array $pieces)
• This function Join array elements with a ‘glue’ string.
• Returns a string containing a string representation of all the array elements in the
same order, with the glue string between each element.
For example:
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated;
?>
Output:
lastname,email,phone
• The join() is an alias of implode() function.
2.28
Web Technologies - I Function and String

3. strtok() Function:
• The strtok() function splits a string into smaller strings (tokens). It gives us new token
each time.
Syntax: string strtok (string $str, string $separator)
• The strtok() function splits a string ‘str’ into smaller strings (tokens), with each token
being delimited by any character from ‘separator’.
• That is, if we have a string like "This is an example string" we could tokenize this string
into its individual words by using the space character as the separator.
• Note that only the first call to strtok() uses the string argument. Every subsequent call
to strtok() only needs the separator to use, as it keeps track of where it is in the current
string.
For example:
<?php
$string = "lastname,email,phone";
$token = strtok($string, ",");
while ($token !== false)
{
echo "$token <br>";
$token = strtok(",");
}
?>
Output:
lastname
email
phone
• In the above program, the character ‘,’ we use as the separator, because we want to
break the string by ‘,’. Inside while loop we display each token of the string. When
there are no more tokens to be return this function returns false.
4. sscanf() Function: [April 16]
• This function in PHP decomposes a string.
• The sscanf() function parses a string into variables based on the format string.
Syntax: sscanf(string,format,arg1,arg2,arg++)
For example:
<?php
$str = "If you divide 4 by 2 you'll get 2";
$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");
print_r($format);
?>
Output:
Array ( [0] => If [1] => you [2] => divide [3] => 4 [4]
=> by [5] => 2 [6] => you'll [7] => get [8] => 2 )
2.29
Web Technologies - I Function and String

2.10.2 Searching Functions


• PHP has many functions to work with strings. The most commonly used functions for
searching are explained in this section.
1. strpos() Function:
• This function finds the position of the first occurrence of a substring in a string.
Syntax: mixed strpos(string $str, mixed $find[, int $offset = 0])
• Find the numeric position of the first occurrence of ‘find’ in the ‘str’ string. Mixed
means any PHP data type.
• If ‘find’ is not a string, it is converted to an integer and applied as the ordinal value of a
character.
• ‘offset’ specifies that, search will start this number of characters counted from the
beginning of the string.
• The function returns the position of where the ‘find’ exists relative to the beginning of
the ‘str’ string (independent of offset). Also note that string positions start at 0 and
not 1.
• Returns False if the ‘find’ was not found.
For example:
<?php
echo strpos("I am a PHP programmer", "am");
echo “<br>”;
echo strpos("I am a PHP programmer", "am", 5);
?>
Output:
2
16
• In the above program the position (index) of character ‘I’ is 0, hence it displays
th
position of ‘am’ is 2. In the second case, searching starts from 5 character, hence ‘am’
is at position 16.
2. strrpos() Function: [Oct. 11]
• The syntax of this function is same as strpos() function. This function finds the last
occurrence of substring in the main string.
For example:
<?php
echo strrpos("I am a PHP programmer", "am");
echo “<br>”;
echo strrpos("I am a PHP programmer", "am", 5);
?>
Output:
16
16
2.30
Web Technologies - I Function and String

3. strstr() Function:
• This function finds the first occurrence of a small string and returns from that small
string onwards.
Syntax: string strstr (string $str, mixed $find)
• Returns part of ‘str’ string the matching point and including the first occurrence of
‘find’ word to the end of ‘str’.
For example:
<?php
$str="w3resource.com";
$newstring = strstr($str,".");
echo $newstring;
?>
Output:
.com
• Few more searching functions are:
1. stristr() : Case-insensitive version of strstr() function.
2. strchr() : Alias of strstr().
3. strrchr() : Find last occurrence of a character in a string.
Decomposing URLs:
• The parse_url() function returns an array of components of a URL:
Syntax: $array = parse_url(url);
For example:
<?php
$bits = parse_url('http://me:secret@example.com:8080/
php/test?user=Amar#res');
print_r($bits);
?>
Output:
Array ( [scheme] => http
[host] => example.com
[port] => 8080
[user] => me
[pass] => secret
[path] => /php/test
[query] => user=Amar
[fragment] => res
)
2.31
Web Technologies - I Function and String

2.11 REGULAR EXPRESSIONS [Oct. 16]

• Regular expression is string that represents a pattern. PHP provides two different
types of regular expressions:
1. POSIX Regular Expression and
2. Perl compatible Regular Expression.
• POSIX regular expressions are less powerful, and sometimes slower, than the Perl-
compatible functions, but can be easier to read.
• There are following three uses of the regular expressions:
1. matching: To match the given pattern.
2. substituting: Substitution of new text for the matching text.
3. splitting: Splitting a string into an array of smaller chunks.
• Regular expression functions accept two parameters. First is pattern and second is
string to be matched with pattern.
For example:
ereg(‘students’, ‘Hello students’);
// returns true
• Some special characters are also used to perform the matching like ∧ (start of string), $
(end of string), · (matches any single character).
• Regular expressions are case-sensitive by default. If we want case-insensitive then use
eregi().
1. For matching : The ereg() and eregi() functions are useful.
2. For replacing : The ereg_replace() is used. This function takes the pattern and
replacement string and a string in which to search and returns
replace string.
3. For splitting : The split() is use to divide a string into smaller chunks, which
are returned as an array.
• Let us see some functions in detail.
1. ereg() Function: [Oct. 17]
• The ereg() function is used for regular expression match.
Syntax: int ereg (string $pattern , string $input_str [, array &$regs])
• The first parameter ‘pattern’ is a regular expression. The function searches an
‘input_str’ for matches to the regular expression given in ‘pattern’ in a case-sensitive
way.
• If matches are found for parenthesized substrings of ‘pattern’ and the function is
called with the third argument ‘regs’, the matches will be stored in the elements of the
array ‘regs’.
2.32
Web Technologies - I Function and String

• $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2]
will contain the substring starting at the second, and so on. The $regs[0] will contain a
copy of the complete string matched.
• Returns the length of the matched string if a match for ‘pattern’ was found in input_str
or false if no matches were found or an error occurred.
• If the optional parameter ‘regs’ was not passed or the length of the matched string is 0,
this function returns 1.
• The following example takes a date in ISO format (YYYY-MM-DD) and prints it in
DD.MM.YYYY format:
For example:
<?php
$date = "2015-04-12";
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs))
{
echo "$regs[3].$regs[2].$regs[1]";
}
else
{
echo "Invalid date format: $date";
}
?>
Output:
12.04.2015
• To specify a set of acceptable characters in your pattern, we can either build a
character class yourself or use a predefined one.
• In PHP we can create our own character class by enclosing the acceptable characters
in square brackets.
For example:
ereg(‘C[aeiou]t’, ‘cut) // returns true
ereg(‘c[aeiou]t’, ‘crt’) // returns false
ereg('[0-9]%', 'we are 25% complete'); // returns true
• In character classes ‘∧
∧’ is used for negation.
For example:
ereg(‘c[∧aeiou]t’, ‘cut’) // returns false
• In regular expressions a caret (^) at the beginning of a regular expression indicates
that it must match the beginning of the string.
2.33
Web Technologies - I Function and String

For example:
ereg(‘^PHP’, ‘I am a PHP programmer’) // returns false
ereg(‘^PHP’, ‘PHP programmer’) // returns true
• Similarly, a dollar sign ($) at the end of a regular expression means that it must match
the end of the string
For example:
ereg(‘PHP$’, ‘Programming in PHP’) // returns true
• We can define a range of characters with a hypen (−)
For example:
ereg(‘c[a-z]t’, ‘cat’); // returns true
‘/’ (pipe) character is used to specify alternatives in a regular expression.
ereg(‘A|B’, ‘A’) // returns true
• To specify a repeating pattern, we can use quantifiers. Following table lists qualifiers:
Quantifier Meaning
? 0 or 1
* 0 or more
+ 1 or more
{n} exactly n times
{n, m} atleast n, no more than m times
{n, } atleast n times.
For example:
ereg(‘ca+t’, ‘caaat’); // true
ereg(‘ca*t’, ‘ct’); // true
ereg(‘ca+t’, ‘ct’); // false
2. ereg_replace() Function:
• The ereg_replace() function takes a ‘pattern’, a ‘replacement’ string, and a ‘string’ in
which to search.
• If ‘pattern’ found in the string ‘string’ then it is replaced by the string ‘replacement’.
This function returns the modified string.
Syntax:
string ereg_replace(string $pattern, string $replacement, string $string)
For example:
<?php
$num = "7";
$str = ereg_replace("seven", $num, "There are seven days in a week");
echo $str;
?>
Output:
There are 7 days in a week
• The eregi_replace() function is a case-insensitive form of ereg_replace().
2.34
Web Technologies - I Function and String

3. split() Function: [April 19]


• The split() function uses a regular expression to divide a string into smaller chunks,
which are returned as an array.
Syntax: $chunks = split(pattern, string [, limit ]);
• The pattern matches the text that separates the chunks.
For example:
<?php
$expression = '3*5+i/6-12';
$terms = split('[/+*-]', $expression);
print_r($terms);
?>
Output:
Array ([0] => 3 [1] => 5 [2] => i [3] => 6 [4] => 12)
• If ‘limit’ is set, the returned array will contain a maximum of ‘limit’ elements with the
last element containing the whole rest of string.
For example:
<?php
$expression = '3*5+i/6-12';
$terms = split('[/+*-]', $expression, 3);
print_r($terms);
?>
Output:
Array ( [0] => 3 [1] => 5 [2] => i/6-12 )
• The ereg(), ereg_replace(), and split() function has been deprecated as of PHP 5.3.0.
Relying on this feature is highly discouraged.
Perl-Compatible Regular Expressions: [April 17]
• POSIX regular expressions are designed for use with only textual data. To do matches
against arbitrary binary data, we will need to use Perl-compatible regular expressions.
• The functions described above i.e. ereg(), ereg_replace(), and split() use the POSIX
regular expression for matching, replacing and splitting.
• The corresponding Perl-Compatible Regular expression functions are preg_match(),
preg_replace(), and preg_split().
• Perl-style regular expressions use the Perl syntax for patterns, which means that each
pattern must be enclosed in a pair of delimiters.
• Traditionally, the slash (/) character is used; for example, /pattern/. The other
delimiters are #...#, (), {}, [], and <>.
2.35
Web Technologies - I Function and String

For example:
preg_match('#PHP#', 'I am a PHP programmer'); // returns true
echo preg_replace('/,/', '+', 'a,b,c'); // Displays a+b+c
print_r(preg_split('/-/', '12-04-2015'));
Output:
Array ( [0] => 12 [1] => 04 [2] => 2015 )

PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. The [:alpha:] can also be specified as,
(a) [A-Za-z0-9] (b) [A-za-z]
(c) [A-z] (d) [a-z]
2. A function in PHP which starts with double underscore is known as,
(a) Magic Function (b) Inbuilt Function
(c) Default function (d) User Defined Function
3. A function name always begins with the keyword,
(a) fun (b) def
(c) function (d) None of mentioned
4. A variable $str is set to "HELLO WORLD", which of the following script returns it
title case,
(a) echo ucwords($str) (b) echo ucwords(strtolower($str)
(c) echo ucfirst($str) (d) echo ucfirst(strtolower($str)
5. How many types of functions are available in PHP?
(a) 5 (b) 4
(c) 3 (d) 2
6. POSIX stands for,
(a) Portable Operating System Interface for Unix
(b) Portable Operating System Interface for Linux
(c) Portative Operating System Interface for Unix
(d) Portative Operating System Interface for Linux
7. The strstr [egg] function selects a substring by its,
(a) Numerical value (b) Content
(c) Position (d) zero
8. Which function compares the two strings s1 and s2, ignoring the case of the
characters?
(a) strtolower() (b) toLowerCase()
(c) strcasecmp() (d) lc()
9. Which function can be used to compare two strings using a case-insensitive binary
algorithm?
(a) strcmp() (b) strcmp()
(c) strcasecmp() (d) stristr()
2.36

You might also like