WEB TECHNOLOGY-1 chp 2
WEB TECHNOLOGY-1 chp 2
WEB TECHNOLOGY-1 chp 2
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
Web Technologies - I Function and String
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
?>
• 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.
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.
• 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]
• 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
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
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
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”
For example:
$input = <<< end
"Programming PHP" by Nirali
end;
echo htmlentities($input);
// "Programming PHP" by Nirali
echo htmlentities($input, ENT_QUOTES);
// "Programming PHP" by O'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 &
o " (double quote) becomes "
o ' (single quote) becomes '
o < (less than) becomes <
o > (greater than) becomes >
• 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; // <a href='test'>Test</a>
?>
2.20
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
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======="
?>
• 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
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
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
• 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
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