Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

PHP Unit 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

PHP Unit 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

PHP Unit 2 1 GSC BCA

Contents
Function ........................................................................................................................................................ 3
Advantage of function:........................................................................................................................ 3
Function Definition/Creating a Function .................................................................................... 3
Function call/Calling a function ...................................................................................................... 4
Variable Scope: ........................................................................................................................................... 4
Local variable ......................................................................................................................................... 4
Global variable ....................................................................................................................................... 5
Static .......................................................................................................................................................... 6
Function Parameters or Arguments .................................................................................................. 6
Passing Parameters by value/Call by value ............................................................................... 7
Passing Parameters by Reference .................................................................................................. 7
Setting Default Values for Function parameter ........................................................................ 8
Returning Values from Functions ....................................................................................................... 8
Variable Function ...................................................................................................................................... 9
Type Hinting ................................................................................................................................................ 9
Anonymous function .............................................................................................................................. 10
PHP String .................................................................................................................................................. 11
Single Quoted ....................................................................................................................................... 11
Double Quoted ..................................................................................................................................... 11
Heredoc .................................................................................................................................................. 11
Accessing Individual Characters ....................................................................................................... 12
Cleaning Strings ....................................................................................................................................... 12
Removing Whitespace ...................................................................................................................... 12
Changing Case ...................................................................................................................................... 13
Encoding and Escaping ......................................................................................................................... 14
HTML ....................................................................................................................................................... 14
Entity-quoting all special characters .......................................................................................... 14
Entity-quoting only HTML syntax characters ......................................................................... 14
Removing HTML tags ........................................................................................................................ 15
Extracting meta tags .......................................................................................................................... 15
Comparing Strings .................................................................................................................................. 16
PHP Unit 2 2 GSC BCA

Exact Comparisons............................................................................................................................. 16
Approximate Equality ....................................................................................................................... 17
Manipulating and Searching Strings ................................................................................................ 18
Substrings .............................................................................................................................................. 18
Miscellaneous String Functions .................................................................................................... 20
Decomposing a String ....................................................................................................................... 21
String-Searching Functions ............................................................................................................ 22
Regular Expression ................................................................................................................................. 25
Regular Expression Functions ....................................................................................................... 25
Regular expression quantifiers ..................................................................................................... 26
Character classes ................................................................................................................................ 26
Anchors................................................................................................................................................... 26
PHP Unit 2 3 GSC BCA

Unit 2 – Functions & Strings

Functions & Strings: Calling a function – defining a function – variable scope –


function parameters – return values – variable functions – anonymous functions -
User defined function
Strings: Accessing individual characters – cleaning strings – encoding and escaping
– comparing strings – manipulating and searching strings – regular expression.

Function
A function is a block of code written in a program to perform some specific task. They
take information as parameter, execute a block of statements or perform operations on
this parameters and returns the result.

PHP provides us with two major types of functions:

 Built-in functions : PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of functions. To
use those we just need to call them as per our requirement like, var_dump,
fopen(), print_r(), gettype() and so on.
 User Defined Functions: Apart from the built-in functions, PHP allows us to
create our own customised functions called the user-defined functions. Using
this we can create our own packages of code and use it wherever necessary by
simply calling it.

Advantage of function:
 Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
 Less Code: It saves a lot of code because you don't need to write the logic many
times.
 Easy to understand: PHP functions separate the programming logic. So it is
easier to understand the flow of the application.
 Easier error detection: Since, our code is divided into functions, we can easily
detect in which function, and the error could lie and fix them fast and easily.
 Easily maintained: If anything or any line of code needs to be changed, we can
easily change it inside the function and the change will be reflected everywhere.

Function Definition/Creating a Function


 A function name always begins with the keyword function.
 The opening curly brace ‘{‘ indicates the beginning of the function code, and the
closing curly brace ‘}’ indicates the end of the function.
 To call a function we just need to write its name followed by the parenthesis
 A function name cannot start with a number. It can start with an alphabet or
underscore.
 A function name is not case-sensitive.
PHP Unit 2 4 GSC BCA

Syntax:

function function_name()
{
executable code;
}

Example:

<?php
function writeMessage()
{
echo "Hello world!";
}
?>

Function call/Calling a function


To call the function, just write its name followed by parentheses ():

Example

<?php
function writeMessage()
{
echo "Hello world!";
}
writeMessage();
?>

Output: Hello world!

Variable Scope:
Scope of variable is the part of PHP script where the variable can be accessed or used.
PHP supports three different scopes for a variable. These scopes are-

1. Local
2. Global
3. Static

Local variable
A variable declared within the function has local scope. That means this variable is only
used within the function body. This variable is not used outside the function.

function localscope()
{
$var = 5; //local scope
PHP Unit 2 5 GSC BCA

echo '<br> The value of $var inside the function is: '. $var;
}
localscope(); // call the function
echo '<br> The value of $var inside the function is: '. $var;
The output will be:

The value of $var inside the function is: 5


The value of $var inside the function is:

Global variable
If a variable is defined outside of the function, then the variable scope is global. By
default, a global scope variable is only available to code that runs at global level. That
means, it is not available inside a function.

<?php
$globalscope = 20;
function localscope()
{
echo '<br> The value of global scope variable is :'.$globalscope;
}
localscope(); // call the function
echo '<br> The value of $globalscope outside the function is: '. $globalscope;
?>

Then the output will be:

The value of global scope variable is :


The value of $globalscope outside the function is: 20

To access a global variable from within a function global statement is used. The global
statement import a variable from global scope to local scope.

$globalscope = 20;
function localscope()
{
global $globalscope;
echo '<br> The value of global scope variable is :'.$globalscope;
}
localscope();
echo '<br> The value of $globalscope outside the function is: '. $globalscope;

The output will be:

The value of global scope variable is :20


The value of $globalscope outside the function is: 20
PHP Unit 2 6 GSC BCA

Static
Generally when function is completed, all of its variable is wiped out. In case a function
executes many times, each time the function start with fresh copy of variable and the
previous value has no effect. Sometimes it can be required to not delete the local
variable. This variable may be required to use for further task. Static keyword is used to
retain the variable. Note that the scope of static is local. Static variable is assigned only
with predetermined values.

function localscope()
{
static $var = 5; //local scope
echo '<br> The value of static variable $var inside the function is: '. $var;
$var++;
}
localscope(); // call the function
localscope(); // call the function
localscope(); // call the function
// using $var outside the function will generate an error
echo '<br> The value of $var inside the function is: '. $var;

Then the output will be

The value of static variable $var inside the function is: 5


The value of static variable $var inside the function is: 6
The value of static variable $var inside the function is: 7
( ! ) Notice: Undefined variable: var
The value of $var inside the function is:

Function Parameters or Arguments


 The information or variable, within the function’s parenthesis, are called
parameters.
 These are used to hold the values executable during runtime.
 A user is free to take in as many parameters as he wants, separated with a
comma(,) operator.
 While passing the values like during a function call, they are called arguments.
 An argument is a value passed to a function and a parameter is used to hold
those arguments.
 In common term, both parameter and argument mean the same. We need to keep
in mind that for every parameter, we need to pass its corresponding argument.

There are two different ways to pass parameters to a function. The first, and more
common, is by value. The other is by reference.
PHP Unit 2 7 GSC BCA

Passing Parameters by value/Call by value


On passing arguments using pass by value, the value of the argument gets changed
within a function, but the original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.

Example:

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

Output:

Sum of the two numbers is : 30

Passing Parameters by Reference


On passing arguments as pass by reference, the original value is passed. Therefore, the
original value gets altered. In pass by reference we actually pass the address of the
value, where it is stored using ampersand sign ‘&’.

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

This will display following result

Original Value is 10
Original Value is 16
PHP Unit 2 8 GSC BCA

Setting Default Values for Function parameter


PHP allows us to set default argument values for function parameters. If we do not pass
any argument for a parameter with default value then PHP will use the default set value
for this parameter in the function call.

Example:

<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

Output:

Hello Rajesh
Hello Sonoo
Hello John

Returning Values from Functions


Functions can also return values to the part of program from where it is called. The
return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The
return statement also marks the end of the function and stops the execution after that
and returns the value.

Example:

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

This will display following result


Returned value from the function : 30
PHP Unit 2 9 GSC BCA

Variable 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. This feature is useful in
implementing callbacks, function tables etc.

Example

<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>

Output
This will produce following result.

30

Type Hinting
Type hinting is a concept that provides hints to function for the expected data type of
arguments.

For example, If we want to add an integer while writing the add function, we had
mentioned the data type (integer in this case) of the parameter. While calling the
function we need to provide an argument of integer type only. If you provide data of any
other type, it will throw an error with clear instructions that the value of an integer type
is needed.

Example:

<?php
function add(array $numbers){
$sum=0;
foreach($numbers as $item){
$sum=$sum+$item;
}
echo $sum;
}
add(array(10,10));
?>

Output: 20

If an integer is passed, the error is thrown.


PHP Unit 2 10 GSC BCA

Anonymous function
Anonymous function is a function without any user defined name. Such a function is
also called closure or lambda function. Most common use of anonymous function is to
create an inline callback function.

Syntax

$var=function ($arg1, $arg2) { return $val; };

Example

<?php

$var = function ($x) {return pow($x,3);};


echo "cube of 3 = " . $var(3);
?>

Output

This will produce following result. cube of 3 = 27


PHP Unit 2 11 GSC BCA

PHP String
PHP string is a sequence of characters. Everything inside quotes, single (‘ ‘) and double
(” “) in PHP is treated as a string. There are 3 ways to specify a string literal in PHP.

1. single quoted
2. double quoted
3. heredoc syntax

Single Quoted
This type of string does not process special characters inside quotes.

<?php
$str=”PHP”;
echo ‘Hello, $str’;
?>

Output: Hello, $str

Double Quoted
Unlike single-quote strings, double-quote strings in PHP are capable of processing
special characters.

<?php
$str="PHP";
echo “Hello, $str”;
?>

Output: Hello, PHP

Escape Sequence

The character begins with a backslash(“\”) is treated as escape sequences and is


replaced with special characters. Here are few important escape sequences.

“\n” is replaced by a new line


“\t” is replaced by a tab space
“\$” is replaced by a dollar sign
“\r” is replaced by a carriage return
“\\” is replaced by a backslash
“\”” is replaced by a double quote
“\'” is replaced by a single quote

Heredoc
The syntax of Heredoc (<<<) is another way to delimit PHP strings. An identifier is given
after the heredoc (<<< ) operator, after which any text can be written as a new line is
started. To close the syntax, the same identifier is given without any tab or space.
PHP Unit 2 12 GSC BCA

<?php

$input = <<<testHeredoc
Welcome to PHP.
Started writing programme in PHP!.
I am enjoying this.
testHeredoc;

echo $input;
?>

Output:
Welcome to PHP.
Started writing programme in PHP!.
I am enjoying this.

Accessing Individual Characters


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

$string = 'Hello, world';


$length = strlen($string); // $length is 12

You can use the string offset syntax on a string to address individual characters:

$string = 'Hello';
for ($i=0; $i < strlen($string); $i++) {
printf("The %dth character is %s\n", $i, $string{$i});
}

The 0th character is H


The 1th character is e
The 2th character is l
The 3th character is l
The 4th character is o

Cleaning Strings
Often, the strings we get from files or users need to be cleaned up before we can use
them. Two common problems with raw data are the presence of extraneous whitespace
and incorrect capitalization (uppercase versus lowercase).

Removing Whitespace
You can remove leading or trailing whitespace with the trim(), ltrim(), and rtrim()
functions:

$trimmed = trim(string [, charlist ]);


$trimmed = ltrim(string [, charlist ]);
$trimmed = rtrim(string [, charlist ]);
PHP Unit 2 13 GSC BCA

trim() returns a copy of string with whitespace removed from the beginning and the
end. ltrim() (the l is for left) does the same, but removes whitespace only from the start
of the string. rtrim() (the r is for right) removes whitespace only from the end of the
string.

Default characters removed by trim(), ltrim(), and rtrim()

Character ASCII value Meaning


"" 0x20 Space
"\t" 0x09 Tab
"\n" 0x0A Newline (line feed)
"\r" 0x0D Carriage return
"\0" 0x00 NUL-byte
"\x0B" 0x0B Vertical tab

For example:

$title = " Programming PHP \n";


$str1 = ltrim($title); // $str1 is "Programming PHP \n"
$str2 = rtrim($title); // $str2 is " Programming PHP"
$str3 = trim($title); // $str3 is "Programming PHP"

Given a line of tab-separated data, use the charlist argument to remove leading or
trailing whitespace without deleting the tabs:

$record = " Fred\tFlintstone\t35\tWilma\t \n";


$record = trim($record, " \r\n\0\x0B");
// $record is "Fred\tFlintstone\t35\tWilma"

Changing Case
$string1 = "FRED flintstone";
$string2 = "barney rubble";
print(strtolower($string1));
print(strtoupper($string1));
print(ucfirst($string2));
print(ucwords($string2));
print(ucwords(strtolower($string1)));

Output:
fred flintstone
FRED FLINTSTONE
Barney rubble
Barney Rubble
Fred Flintstone
PHP Unit 2 14 GSC BCA

Encoding and Escaping


Because PHP programs often interact with HTML pages, web addresses (URLs), and
databases, there are functions to help you 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.

HTML
Special characters in HTML are represented by entities such as &amp; and &lt;. There
are two PHP functions that turn special characters in a string into their entities: one for
removing HTML tags, and one for extracting only meta tags.

Entity-quoting all special characters


PHP htmlentities() function is a string function, which is used to convert character to
HTML entities. This includes the lessthan sign (<), the greater-than sign (>), the
ampersand (&), and accented characters.

Example:

<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';
echo htmlentities($str);
?>

The HTML output of the code above will be (View Source):

&lt;a href=&quot;https://www.w3schools.com&quot;&gt;Go to
w3schools.com&lt;/a&gt;

The browser output of the code above will be:

<a href="https://www.w3schools.com">Go to w3schools.com</a>

Entity-quoting only HTML syntax characters


The htmlspecialchars() function converts all pre-defined characters to the HTML
entities. The following entities are converted:

• Ampersands (&) are converted to &amp;


• Double quotes (") are converted to &quot;
• Single quotes (') are converted to &#039;
• Less-than signs (<) are converted to &lt;
• Greater-than signs (>) are converted to &gt;
PHP Unit 2 15 GSC BCA

Example:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>

The HTML output of the code above will be (View Source):

<!DOCTYPE html>
<html>
<body>
This is some &lt;b&gt;bold&lt;/b&gt; text.
</body>
</html>

The browser output of the code above will be:

This is some <b>bold</b> text.

Removing HTML tags


The strip_tags() function removes HTML tags from a string:

Example 1:
$input = '<p>Howdy, &quot;Cowboy&quot;</p>';
$output = strip_tags($input);

Output: 'Howdy, &quot;Cowboy&quot;'

Example 2:

$input = 'The <b>bold</b> tags will <i>stay</i><p>';


$output = strip_tags($input, '<b>');

Output: The <b>bold</b> tags will stay

Extracting meta tags


The get_meta_tags() function returns an array of the meta tags for an HTML page,
specified as a local filename or URL. The name of the meta tag (keywords, author,
description, etc.) becomes the key in the array, and the content of the meta tag becomes
the corresponding value:

$metaTags = get_meta_tags('http://www.example.com/');

echo "Web page made by {$metaTags['author']}";

Output: Web page made by John Doe


PHP Unit 2 16 GSC BCA

Comparing Strings
PHP has two operators and six functions for comparing strings to each other.

Exact Comparisons
You can compare two strings for equality with the == and === operators. These
operators differ in how they deal with non-string operands. The == operator casts non-
string operands to strings, so it reports that 3 and "3" are equal. The === operator does
not cast, and returns false if the types of the arguments differ.

$o1 = 3;
$o2 = "3";
if ($o1 == $o2) {
echo("== returns A<br>");
}
if ($o1 === $o2) {
echo("=== returns B<br>");
}

Output: == returns A

The comparison operators (<, <=, >, >=) also work on strings:

$him = "Fred";
$her = "Wilma";
if ($him < $her) {
print "$him comes before $her in the alphabet.\n";
}

Output: Fred comes before Wilma in the alphabet

However, the comparison operators give unexpected results when comparing strings
and numbers:

$string = "PHP Rocks";


$number = 5;
if ($string < $number) {
echo("$string < $number");
}

Output: PHP Rocks < 5

When one argument to a comparison operator is a number, the other argument is cast
to a number. This means that "PHP Rocks" is cast to a number, giving 0 (since the string
does not start with a number). Because 0 is less than 5, PHP prints "PHP Rocks < 5".

To explicitly compare two strings as strings, casting numbers to strings if necessary, use
the strcmp( ) function:
PHP Unit 2 17 GSC BCA

$relationship = strcmp(string_1, string_2);

The function returns a number less than 0 if string_1 sorts before string_2, greater than
0 if string_2 sorts before string_1, or 0 if they are the same:

$n = strcmp("PHP Rocks", 5);


echo($n);

Output: 1

A variation on strcmp( ) is strcasecmp( ) , which converts strings to lowercase before


comparing them. Its arguments and return values are the same as those for strcmp( ):

$n = strcasecmp("Fred", "frED"); // $n is 0

Approximate Equality
PHP provides several functions that let you test whether two strings are approximately
equal: soundex( ) , metaphone( ), similar_text(), and levenshtein( ).

$soundex_code = soundex($string);
$metaphone_code = metaphone($string);
$in_common = similar_text($string_1, $string_2 [, $percentage ]);
$similarity = levenshtein($string_1, $string_2);
$similarity = levenshtein($string_1, $string_2 [, $cost_ins, $cost_rep, $cost_del ]);

To see whether two strings are approximately equal with these algorithms, compare
their pronunciations. You can compare Soundex values only to Soundex values and
Metaphone values only to Metaphone values. The Metaphone algorithm is generally
more accurate, as the following example demonstrates:

Example:

$known = "Fred";
$query = "Phred";
if (soundex($known) == soundex($query)) {
print "soundex: $known sounds like $query<br>";
} else {
print "soundex: $known doesn't sound like $query<br>";
}
if (metaphone($known) == metaphone($query)) {
print "metaphone: $known sounds like $query<br>";
} else {
print "metaphone: $known doesn't sound like $query<br>";
}

Output:
soundex: Fred doesn't sound like Phred
metaphone: Fred sounds like Phred
PHP Unit 2 18 GSC BCA

similar_text( )

The similar_text( ) function returns the number of characters that its two string
arguments have in common. The third argument, if present, is a variable in which to
store the commonality as a percentage:

$string_1 = "Rasmus Lerdorf";


$string_2 = "Razmus Lehrdorf";
$common = similar_text($string_1, $string_2, $percent);
printf("They have %d chars in common (%.2f%%).", $common, $percent);

Output: They have 13 chars in common (89.66%).

The Levenshtein algorithm calculates the similarity of two strings based on how many
characters you must add, substitute, or remove to make them the same. For instance,
"cat" and "cot" have a Levenshtein distance of 1, because you need to change only one
character (the "a" to an "o") to make them the same:

$similarity = levenshtein("cat", "cot"); // $similarity is 1

Manipulating and Searching Strings

Substrings

substr( )
If you know where in a larger string the interesting data lies, you can copy it out with
the substr( ) function:

$piece = substr(string, start [, length ]);

The start argument is the position in string at which to begin copying, with 0 meaning
the start of the string. The length argument is the number of characters to copy (the
default is to copy until the end of the string).

Example:

$name = "Fred Flintstone";


$fluff = substr($name, 6, 4); // $fluff is "lint"
$sound = substr($name, 11); // $sound is "tone"

substr_count( )
To learn how many times a smaller string occurs in a larger one, use substr_count( ) :

$number = substr_count(big_string, small_string);


PHP Unit 2 19 GSC BCA

Example:

$sketch = <<< End_of_Sketch


Well, there's egg and bacon; egg sausage and bacon; egg and spam;
egg bacon and spam; egg bacon sausage and spam; spam bacon sausage
and spam; spam egg spam spam bacon and spam; spam sausage spam spam
bacon spam tomato and spam;
End_of_Sketch;
$count = substr_count($sketch, "spam");
print("The word spam occurs $count times.");

Output: The word spam occurs 14 times.

substr_replace( )
The substr_replace( ) function permits many kinds of string modifications:

$string = substr_replace(original, new, start [, 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 new. If no fourth argument is given,
substr_replace( ) removes the text from start to the end of the string.

Example:

$greeting = "good morning citizen";


$farewell = substr_replace($greeting, "bye", 5, 7);
// $farewell is "good bye citizen"

Use a length value of 0 to insert without deleting:

$farewell = substr_replace($farewell, "kind ", 9, 0);


// $farewell is "good bye kind citizen"

Use a replacement of "" to delete without inserting:

$farewell = substr_replace($farewell, "", 8);


// $farewell is "good bye"

Here’s how you can insert at the beginning of the string:

$farewell = substr_replace($farewell, "now it's time to say ", 0, 0);


// $farewell is "now it's time to say good bye"'

A negative value for start indicates the number of characters from the end of the string
from which to start the replacement:

$farewell = substr_replace($farewell, "riddance", -3);


// $farewell is "now it's time to say good riddance"
PHP Unit 2 20 GSC BCA

A negative length indicates the number of characters from the end of the string at which
to stop deleting:

$farewell = substr_replace($farewell, "", -8, -5);


// $farewell is "now it's time to say good dance"

Miscellaneous String Functions


The strrev( ) function takes a string and returns a reversed copy of it:

$string = strrev(string);

For example:

echo strrev("There is no cabal");

Output: labac on si erehT

The str_repeat( ) function takes a string and a count and returns a new string
consisting of the argument string repeated count times:

$repeated = str_repeat(string, count);

For example, to build a crude horizontal rule:

echo str_repeat('-', 40);

The str_pad( ) function pads one string with another. Optionally, you can say what
string to pad with, and whether to pad on the left, right, or both:

$padded = str_pad(to_pad, length [, with [, pad_type ]]);

The default is to pad on the right with spaces:

$string = str_pad('Fred Flintstone', 30);


echo "$string:35:Wilma";

Output: Fred Flintstone :35:Wilma

The optional third argument is the string to pad with:

$string = str_pad('Fred Flintstone', 30, '. ');


echo "{$string}35";

Output: Fred Flintstone. . . . . . . .35

The optional fourth argument can be either STR_PAD_RIGHT (the default),


STR_PAD_LEFT, or STR_PAD_BOTH (to center). For example:

echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_LEFT) . "]\n";


echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_BOTH) . "]\n";
PHP Unit 2 21 GSC BCA

[ Fred Flintstone]
[ Fred Flintstone ]

Decomposing a String
PHP provides several functions to let you break a string into smaller components. In
increasing order of complexity, they are explode( ), strtok( ), and sscanf( ).

Exploding and imploding

Data often arrives as strings, which must be broken down into an array of values. For
instance, you might want to separate out the comma-separated fields from a string such
as "Fred,25,Wilma". In these situations, use the explode( ) function:

$array = explode(separator, string [, limit]);

The first argument, separator, is a string containing the field separator. The second
argument, string, is the string to split. The optional third argument, limit, is the
maximum number of values to return in the array. If the limit is reached, the last
element of the array contains the remainder of the string:

$input = 'Fred,25,Wilma';
$fields = explode(',', $input);
// $fields is array('Fred', '25', 'Wilma')
$fields = explode(',', $input, 2);
// $fields is array('Fred', '25,Wilma')

The implode( ) function does the exact opposite of explode( )—it creates a large string
from an array of smaller strings:

$string = implode(separator, array);

The first argument, separator, is the string to put between the elements of the second
argument, array. To reconstruct the simple comma-separated value string, simply say:

$fields = array('Fred', '25', 'Wilma');


$string = implode(',', $fields); // $string is 'Fred,25,Wilma'

The join( ) function is an alias for implode( ).

Tokenizing

The strtok( ) function lets you iterate through a string, getting a new chunk (token)
each time. The first time you call it, you need to pass two arguments: the string to iterate
over and the token separator:

$first_chunk = strtok(string, separator);

To retrieve the rest of the tokens, repeatedly call strtok( ) with only the separator:

$next_chunk = strtok(separator);
PHP Unit 2 22 GSC BCA

For instance, consider this invocation:

$string = "Fred,Flintstone,35,Wilma";
$token = strtok($string, ",");
while ($token !== false) {
echo("$token<br>");
$token = strtok(",");
}

Output:
Fred
Flintstone
35
Wilma

sscanf( )

The sscanf( ) function decomposes a string according to a printf( )-like template:

$array = sscanf(string, template);


$count = sscanf(string, template, var1, ... );

If used without the optional variables, sscanf( ) returns an array of fields:

$string = "Fred\tFlintstone (35)";


$a = sscanf($string, "%s\t%s (%d)");
print_r($a);

Output:
Array
(
[0] => Fred
[1] => Flintstone
[2] => 35
)

Pass references to variables to have the fields stored in those variables. The number of
fields assigned is returned:

$string = "Fred\tFlintstone (35)";


$n = sscanf($string, "%s\t%s (%d)", &$first, &$last, &$age);
echo "Matched n fields: $first $last is $age years old";

Output: Fred Flintstone is 35 years old

String-Searching Functions
Several functions find a string or character within a larger string. They come in three
families: strpos( ) and strrpos( ), which return a position; strstr( ), strchr( ), and friends,
which return the string they find; and strspn( ) and strcspn( ), which return how much
of the start of the string matches a mask.
PHP Unit 2 23 GSC BCA

Searches returning position

The strpos( ) function finds the first occurrence of a small string in a larger string:

$position = strpos(large_string, small_string);

If the small string isn’t found, strpos( ) returns false.

The strrpos( ) function finds the last occurrence of a character in a string. It takes the
same arguments and returns the same type of value as strpos( ).

For instance:

$record = "Fred,Flintstone,35,Wilma";
$pos = strrpos($record, ","); // find last comma
echo("The last comma in the record is at position $pos");

Output: The last comma in the record is at position 18

If you pass a string as the second argument to strrpos( ), only the first character is
searched for. To find the last occurrence of a multicharacter string, reverse the strings
and use strpos( ):

$long = "Today is the day we go on holiday to Florida";


$to_find = "day";
$pos = strpos(strrev($long), strrev($to_find));
if ($pos === false) {
echo("Not found");
} else {
// $pos is offset into reversed strings
// Convert to offset into regular strings
$pos = strlen($long) - $pos - strlen($to_find);;
echo("Last occurrence starts at position $pos");
}

Output: Last occurrence starts at position 30

Searches returning rest of string

The strstr( ) function finds the first occurrence of a small string in a larger string and
returns from that small string on. For instance:

$record = "Fred,Flintstone,35,Wilma";

$rest = strstr($record, ","); // $rest is ",Flintstone,35,Wilma"

The variations on strstr( ) are:

stristr( ) Case-insensitive strstr( )


strchr( ) Alias for strstr( )
strrchr( ) Find last occurrence of a character in a string
PHP Unit 2 24 GSC BCA

Searches using masks

If you thought strrchr( ) was esoteric, you haven’t seen anything yet. The strspn( ) and
strcspn( ) functions tell you how many characters at the beginning of a string are
comprised of certain characters:

$length = strspn(string, charset);

For example, this function tests whether a string holds an octal number:

function is_octal ($str) {


return strspn($str, '01234567') == strlen($str);
}

The c in strcspn( ) stands for complement—it tells you how much of the start of the
string is not composed of the characters in the character set. Use it when the number of
interesting characters is greater than the number of uninteresting characters. For
example, this function tests whether a string has any NUL-bytes, tabs, or carriage
returns:

function has_bad_chars ($str) {


return strcspn($str, "\n\t\0");
}

Decomposing URLs

The parse_url( ) function returns an array of components of a URL:

$array = parse_url(url);

For example:

$bits = parse_url('http://me:secret@example.com/cgi-bin/board?user=fred);
print_r($bits);

Output:

Array
(
[scheme] => http
[host] => example.com
[user] => me
[pass] => secret
[path] => /cgi-bin/board
[query] => user=fred
)
PHP Unit 2 25 GSC BCA

Regular Expression
Regular expressions commonly known as a regex (regexes) are a sequence of characters
describing a special search pattern in the form of text string.

Regular Expression Functions


PHP provides a variety of functions that allow you to use regular expressions.

The most common functions are:

Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string,
which may also be 0

preg_replace() Returns a new string where matched patterns have been replaced
with another string

Example:

Some characters have special meanings in regular expressions. For instance, a caret (^)
at the beginning of a regular expression indicates that it must match the beginning of
the string (or, more precisely, anchors the regular expression to the beginning of the
string):

preg_match("/^cow/", "Dave was a cowhand"); // returns false


preg_match("/^cow/", "cowabunga!"); // returns true

Similarly, a dollar sign ($) at the end of a regular expression means that it must match
the end of the string (i.e., anchors the regular expression to the end of the string):

preg_match("/cow$/", "Dave was a cowhand"); // returns false


preg_match("/cow$/", "Don't have a cow"); // returns true

A period (.) in a regular expression matches any single character:

preg_match("/c.t/", "cat"); // returns true


preg_match("/c.t/", "cut"); // returns true
preg_match("/c.t/", "c t"); // returns true
preg_match("/c.t/", "bat"); // returns false
preg_match("/c.t/", "ct"); // returns false

If you want to match one of these special characters (called a metacharacter), you have
to escape it with a backslash:

preg_match("/\$5\.00", "Your bill is $5.00 exactly"); // returns true


preg_match("/$5.00", "Your bill is $5.00 exactly"); // returns false
PHP Unit 2 26 GSC BCA

Regular expression quantifiers


To specify a repeating pattern, you use something called a quantifier. The quantifier
goes after the pattern that’s repeated and says how many times to repeat that pattern.

Quantifier Meaning
? 0 or 1
* 0 or more
+ 1 or more
{n} Exactly n times
{n,m} At least n, no more than m times
{ n ,} At least n times

Character classes

Class Description Expansion


[:alnum:] Alphanumeric characters [0-9a-zA-Z]
[:alpha:] Alphabetic characters (letters) [a-zA-Z]
[:ascii:] 7-bit ASCII [\x01-\x7F]
[:blank:] Horizontal whitespace (space, tab) [ \t]
[:cntrl:] Control characters \x01-\x1F]
[:digit:] Digits [0-9]
[:graph:] Characters that use ink to print
(nonspace, noncontrol) [^\x01-\x20]
[:lower:] Lowercase letter [a-z]
[:print:] Printable character
(graph class plus space and tab) [\t\x20-\xFF]
[:punct:] Any punctuation character,
such as the period (.) and
the semicolon (;) [-!"#$%&'()*+,./:;<=>?@[\\\]^_'{|}~]
[:space:] Whitespace (newline, carriage return,
tab, space, vertical tab) [\n\r\t \x0B]
[:upper:] Uppercase letter [A-Z]
[:xdigit:] Hexadecimal digit [0-9a-fA-F]
\s Whitespace [\r\n \t]
\S Nonwhitespace [^\r\n \t]
\w Word (identifier) character [0-9A-Za-z_]
\W Nonword (identifier) character [^0-9A-Za-z_]
\d Digit [0-9]
\D Nondigit [^0-9]

Anchors
An anchor limits a match to a particular location in the string (anchors do not match
actual characters in the target string). Table 4-8 lists the anchors supported by regular
expressions.

Anchor Matches
^ Start of string
$ End of string
[[:<:]] Start of word
PHP Unit 2 27 GSC BCA

[[:>:]] End of word


\b Word boundary (between \w and \W or at start or end of string)
\B Nonword boundary (between \w and \w, or \W and \W)
\A Beginning of string
\Z End of string or before \n at end
\z End of string
^ Start of line (or after \n if /m flag is enabled)
$ End of line (or before \n if /m flag is enabled)

You might also like