Documente Academic
Documente Profesional
Documente Cultură
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also
accessible from outside the function
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
$_SERVER['REQUEST_METHOD'] - Returns the request method used to access the
page (such as POST)
4. Name any four built-in functions in PHP. [N/D 15]
array() - Creates an array
cal_days_in_month() - Returns the number of days in a month for a specified year and
calendar
date.timezone - The default timezone (used by all date/time functions)
chdir() - Changes the current directory
5. Define XML.
Extensible Markup Language (XML) is a markup language that defines a set of rules
for encoding documents in a format that is both human-readable and machine-readable. It
is defined by the W3C's XML 1.0 Specification and by several other related
specifications, all of which are free open standards.
The basic building block of an XML document is an element, defined by tags. An
element has a beginning and an ending tag. All elements in an XML document are
contained in an outermost element known as the root element.
6. Define DTD.
A document type definition (DTD) is a set of markup declarations that define a
document type for an SGML-family markup language (SGML, XML, and HTML). A
Document Type Definition (DTD) defines the legal building blocks of an XML
document. It defines the document structure with a list of legal elements and attributes.
7. What are the XML rules for distinguishing between the content of a document and
the XML markup element?
The start of XML markup elements is identified by either the less than symbol (<)
or the ampersand (&) character.
Three other characters, the greater than symbol (>), the apostrophe or single quote
() and the double quotation marks () are used by XML for markup.
To use these special characters as content within your document, you must use the
corresponding general XML entity.
8. What is DOM?
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a
standard for accessing documents: "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."
9. What is XSLT?
XSLT (ExtensibleStylesheet
Language
Transformations)
is
language
for transforming XML documents into other XML documents, or other formats such
as HTML for web pages, plain text or into XSL Formatting Objects, which may
subsequently be converted to other formats, such as PDF, PostScript and PNG.
10. What is metadata?
Metadata is simply data about data, or, to put it another way, data that describes other
data. Take, for example, an XML document. An XML document contains markup, which
is a form of metadata. Consider this fragment:
<p>The <library-name>foobar</library-name> library contains the routines <routinename>foo()</routine-name> and <routine-name>bar()</routine-name>.</p>
The <p> tag is metadata that tells us that the string it contains is a paragraph. The
<library-name> and <routine-name> tags are metadata that tell us that the strings they
contain are library names and routine names respectively.
11. What are the uses of XLink,Xpath,Xquery?.
XLink is used to create hyperlinks in XML documents.
XPath: provides a common syntax and semantics for functionality shared between XSLT
and XPointer.
XQuery: query language. It facilitates the data extraction from XML documents.
12. Define PHP.
PHP: Hypertext Preprocessor is a server-side scripting language designed for web
development but also used as a general-purpose programming language. PHP code may
be embedded into HTML code, or it can be used in combination with various web
template systems, web content management systems and web frameworks.
PHP code is usually processed by a PHP interpreter implemented as a module in the web
server or as a Common Gateway Interface (CGI) executable.
13. What are the rules to write variables in PHP?
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
an XML language
used
for web
feeds,
while
the Atom
Publishing
Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and updating
web resources. A feed contains entries, which may be headlines, full-text articles,
excerpts, summaries, and/or links to content on a website, along with various metadata.
The Atom format was developed as an alternative to RSS.
15. How to connect a database in PHP?
We should establish a connection to the MySQL database. This is an extremely important
step because if our script cannot connect to its database, our queries to the database will
fail. A good practice when using databases is to set the username, the password and the
database name values at the beginning of the script code. If we need to change them later,
it will be an easy task.
$username="our_username";$password="our_password";$database="our_database";
We should replace "our_username", "our_password" and "our_database" with the
MySQL username, password and database that will be used by our script.
Next we should connect our PHP script to the database. This can be done with the
mysql_connect PHP function:
mysql_connect(localhost,$username,$password);
Part B
1. Write a PHP program to do string manipulations.
Following are valid examples of string
[Nov/Dec15](16)
To ensure all the letters in a specific string were uppercase, we can use the strtoupper()function
as follows:
<?php
$str = "Like a puppet on a string.";
$cased = strtoupper($str);
// Displays: LIKE A PUPPET ON A STRING.
echo $cased;
It is perhaps obvious but still worth noting that numbers and other non-alphabet characters will
not be converted.
The strtolower() function does the exact opposite of strtoupper() and converts a string into all
lowercase letters:
<?php
$str = "LIKE A PUPPET ON A STRING.";
$cased = strtolower($str);
// Displays: like a puppet on a string.
echo $cased;
Likewise when we want to ensure certain words, such as names or titles, just have the first letter
of each word capitalized. For this we can use the ucwords() function:
<?php
$str = "a knot";
$cased = ucwords($str);
// Displays: A Knot
echo $cased;
It is also possible to manipulate the case of just the first letter of a string using the lcfirst() and
ucfirst() functions. If we want the first letter to be lowercase, use lcfirst(). If we want the first
letter to be uppercase, use ucfirst(). The ucfirst() function is probably the most useful since we
can use it to ensure a sentence always starts with a capital letter.
<?php
The XML document above consists of a root element, "shiporder", that contains a
required attribute called "orderid".
The "shiporder" element contains three different child elements: "orderperson", "shipto"
and "item".
The "item" element appears twice, and it contains a "title", an optional "note" element, a
"quantity", and a "price" element.
We will start with the standard XML declaration followed by the xs:s element that defines
a schema:
In the schema above we use the standard namespace (xs), and the URI associated with
this namespace is the Schema language definition, which has the standard value of
http://www.w3.org/2001/XMLSchema.
Next, we have to define the "shiporder" element.
This element has an attribute and it contains other elements, therefore we consider it as a
complex type.
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
</xs:element>
3. List at least five significant differences between DTD and XML schema for defining
XML document structures with appropriate examples.[May/June 16] (8)
XML Schema vs. DTD
DTD, or Document Type Definition, and XML Schema, which is also known as
XSD, are two ways of describing the structure and content of an XML document.
DTD is the older of the two, and as such, it has limitations that XML Schema has
tried to improve.
The first difference between DTD and XML Schema, is namespace awareness;
XML Schema is, while DTD is not.
Namespace awareness removes the ambiguity that can result in having certain
elements and attributes from multiple XML vocabularies, by giving them
namespaces that put the element or attribute into context.
Part of the reason why XML Schema is namespace aware while DTD is not, is
the fact that XML Schema is written in XML, and DTD is not.
Therefore, XML Schemas can be programmatically processed just like any XML
document.
XML Schema also eliminates the need to learn another language, as it is written in
XML, unlike DTD.
Another key advantage of XML Schema, is its ability to implement strong typing.
An XML Schema can define the data type of certain elements, and even constrain
it to within specific lengths or values.
This ability ensures that the data stored in the XML document is accurate.
DTD lacks strong typing capabilities, and has no way of validating the content to
data types.
XML Schema has a wealth of derived and built-in data types to validate content.
It also has uniform data types, but as all processors and validators need to support
these data types, it often causes older XML parsers to fail.
This is good when working with small files, as it allows you to contain both the
content and the schema within the same document, but when it comes to larger
documents, we have to pull content every time while we retrieve the schema. This
can lead to serious overhead that can degrade performance.
DTD
for Document
XSD
1)
DTD stands
Definition.
Type
2)
3)
4)
5)
6)
XSD is extensible.
7)
new language..
8)
[N / D 15] (8)
XML PARSERS:
An XML parser is a software library or package that provides interfaces for client applications to
work with an XML document. The XML Parser is designed to read the XML and create a way
for programs to use XML.
XML parser validates the document and check that the document is well formatted.
Let's understand the working of XML parser by the figure given below:
Clients does not know what methods to call, they just overrides the methods of the API
and place his own code inside method.
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XML VALIDATION:
A well formed XML document can be validated against DTD or Schema.
A well-formed XML document is an XML document with correct syntax. It is very necessary to
know about valid XML document before knowing XML validation.
Valid XML document
5.
List the essential features of XML parsers.
[May/June 16] (8)
XML is widely used in the era of web development. It is also used to simplify data storage and
data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML
If we need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way we can focus on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will
not require any changes to the HTML.
With a few lines of JavaScript code, we can read an external XML file and update the
data content of your web page.
In the real world, computer systems and databases contain data in incompatible formats.
XML data is stored in plain text format. This provides a software- and hardwareindependent way of storing data.
This makes it much easier to create data that can be shared by different applications.
One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.
Large amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.
Different applications can access your data, not only in HTML pages, but also from XML
data sources.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people,
or people with other disabilities.
XHTML
(16)
What is XSL?
XSL is a language for expressing style sheets. An XSL style sheet is, like with CSS, a file
that describes how to display an XML document of a given type.
XSL shares the functionality and is compatible with CSS2 (although it uses a different
syntax).
Advanced styling features, expressed by an XML document type which defines a set of
elements called Formatting Objects, and attributes (in part borrowed from CSS2
properties and adding more complex ones.
This XML file doesn't contain any presentation information, which is contained in the
stylesheet.
Separating the document's content and the document's styling information allows
displaying the same document on different media (like screen, paper, cell phone), and it
also enables users to view the document according to their preferences and abilities, just
by modifying the style sheet.
The Stylesheet
Here are two templates from the stylesheet used to format the XML file. The full
stylesheet (which includes extra information on pagination and margins) is available.
...
<xsl:template match="FX">
<fo:block font-weight="bold">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="speech[@speaker='Arthur']">
<fo:block background-color="blue">
<xsl:value-of select="@speaker"/>:
<xsl:apply-templates/>
</fo:block>
</xsl:template>
...
The stylesheet can be used to transform any instance of the DTD it was designed for.
The first rule says that an FX element will be transformed into a block with a bold
font. <xsl:apply-templates/> is a recursive call to the template rules for the contents of the
current element.
The second template applies to all speech elements that have the speaker attribute set
to Arthur, and formats them as blue blocks within which the value speaker attribute is
added before the text.
XSL TRANSFORMATION
any XML, e.g. yours or other XML languages like SVG, X3D
With XSLT we then can produce some "enriched" or otherwise transformed XML or
directly some other format that is used to render the contents.
An XSLT program is an XML document. It's top-level skeleton looks like this:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
....
</xsl:stylesheet>
Mandatory "elements"
A stylesheet root tag, including version and namespace attributes (as seen in the example
above):
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
Association of XML and an XSLT file
XSLT was already implemented in IE 5.5., i.e. in the last millenium...
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="project.xsl" type="text/xsl" ?>
<yourxml>
....
</yourxml>
There exist various so-called XSLT processors. Most programming languages and all well-know
server-side scripting languages like PHP include an XSLT library. XML editors usually include
an XSLT processor.
Below is the complete code for a simple "Hello XSLT" example.
XML file (source)
hello.xml
<?xml version="1.0"?>
<?xml-stylesheet href="hello.xsl" type="text/xsl"?>
<page>
<title>Hello</title>
<content>Here is some content</content>
<comment>Written by DKS.</comment>
</page>
Wanted result document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REChtml40/strict.dtd">
<html>
<head>
<title>Hello</title>
</head>
<body bgcolor="#ffffff">
<h1 align="center">Hello</h1>
<p align="center"> Here is some content</p>
<hr><i>Written by DKS</i>
</body>
</html>
The XSLT Stylesheet
hello.xslt
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
<html>
<head>
<title> <xsl:value-of select="title"/>
</title>
</head>
<body bgcolor="#ffffff">
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="title">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>
<xsl:template match="content">
<p align="center"> <xsl:apply-templates/> </p>
</xsl:template>
<xsl:template match="comment">
<hr/> <i><xsl:apply-templates/> </i>
</xsl:template>
</xsl:stylesheet>
7. Explain in details about variables in PHP.
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
PHP does a good job of automatically converting types from one to another when
necessary.
PHP has a total of eight data types which we use to construct our variables
Objects are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
Resources are special variables that hold references to resources external to PHP (such
as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a
leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
It produces the following browser output
2.28888 + 2.21112 = 4.5
Boolean
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans
Here are the rules for determine the "truth" of any value not already of the Boolean type
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.
If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed
$my_var = null;
A variable that has been assigned NULL has the following properties
Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
Functions are reusable bits of code that you use throughout a project.
They help to better organize your application as well as eliminate the need to copy/paste
repetitive pieces of code.
In an ideal world an application should not have multiple functions doing the same thing.
PHP has a lot of built in functions and while we are not expected to learn all of them at
once there are some useful functions that can help in everyday programming and we will
start from there.
$string a string of text or a variable containing a string of text. Input must be at least
one character.
$start think of the string as an array starting from [0]. If we wanted to start from the
first character you would enter 0. A negative value will go to the end of the string.
$length (Optional) is the number of characters returned after the start character. If this
value is less than or equal to the start value then it will return false.
<?php
$name = "Matthew ";
echo substr($name, 0, 5); // Matth
echo substr($name, 2); // tthew
echo substr($name, -6, 5); // tthew
?>
CONVERTING STRINGS TO UPPER OR LOWER CASE
Two useful string functions that are simple to use are strtoupper() andstrtolower(), these
functions can convert your strings to all UPPERCASE or all lowercase.
They are very useful for case sensitive operations where you may require all characters to be
lowercase for example.
<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>
Searching for a needle in a haystack!
Sometimes we need to find a substring within a string and to do that we can use strpos.
Syntax
strpos ($haystack,$needle,$offset)
$haystack this is the string in which you are going to find the $needlestarting from [0].
$needle this is what you are going to search for in the $haystack.
$offset (Optional) search will start from this number of characters counted from the
ROUNDING NUMBERS
One of the most commonly used math function is round(). This function rounds numbers with
decimal points up or down. We can round a number to an integer (whole number) or to a floating
point (decimal numbers).
Syntax
round($val, $precision, $mode)
$mode the type of rounding that occurs and can be one of the following for more
details and examples of modes see PHP docs.
<?php
$number = 3.55776232;
echo
round($number) . "<br/>".
// 4
<?php
$number = 3.55776232;
echo
ceil($number) . "<br/>". // 4
floor($number) . "<br/>"; // 3
?>
Both functions require a value and unlike round(), do not have any additional parameters.
GENERATING RANDOM NUMBERS
Another very common math function is rand() which returns a random number between two
numbers.
Syntax
rand($min, $max)
$min (optional) sets the lowest value to be returned. Default is 0
$max (optional) sets the maximum value to be returned. Default returnsgetrandmax().
<?php
echo rand(). "\n"; //10884
echo rand(). "\n"; // 621
echo rand(2, 10); //2
?>
ARRAY FUNCTIONS
Array or array() is itself a function that stores multiple values in to a single variable. Aside from
the array() function there are a number of other functions to manipulate arrays, here we will look
at some of the most common ones.
ADDING NEW ELEMENTS
Adding new elements to the end of an array can be achieved by calling thearray_push() function.
Syntax
array_push($array, $value1, $value2)
$array the array in which you are adding new elements to.
$value1 (required) is the first value to push onto the end of the $array.
$value2 (optional) is the second value to push onto the end of the $array.
$sort_flags (optional) modifies the sorting behavior. For more information see PHP
docs.
"Farcry 4",
"Metal Gear",
"Fallout 4",
"Witcher 3",
"Batman");
sort($games); // array to sort
echo join(", ", $games);
//output - Batman, Fallout 4, Farcry 4, Metal Gear, Witcher 3
?>
In order to echo or print out sorted arrays we can use a function called join()which is an alias of
another function called implode().
join(glue, array) or implode(glue, array) functions return a string from the elements of an array
and both have the same syntax.
glue (optional) also known as a separator is what to put between the array elements.
If you need to sort and reverse the order of any array then you can use a function called rsort(). It
works exactly the same way as sort() except the output is reversed.
<?php
$games = array(
"Farcry 4",
"Metal Gear",
"Fallout 4",
"Witcher 3",
"Batman");
rsort($games); // array to sort
echo join(", ", $games);
//output - Witcher 3, Metal Gear, Farcry 4, Fallout 4, Batman
?>
9. Explain in detail about Cookies.
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A PHP script that sets a cookie might send headers that look something like this
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
The Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded.
The expires field is an instruction to the browser to "forget" the cookie after the given
time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date.
If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].
SETTING COOKIES WITH PHP
PHP provided setcookie() function to set a cookie. This function requires upto six arguments
and should be called before <html> tag. For each cookie this function has to be called
separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments
Name This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value This sets the value of the named variable and is the content that you actually
want to store.
Expiry This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
Path This specifies the directories for which the cookie is valid. A single forward slash
contain at least two periods to be valid. All cookies are only valid for the host and
domain which created them.
Security This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
ACCESSING COOKIES WITH PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
The simplest regular expression is one that matches a single character, such as g, inside
strings such as g, haggle, or bag.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Sr.No
1
[a-z]
It matches any character from lower-case a through lowercase z.
[A-Z]
[a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging
from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character having a specific connotation. The +, *, ?,
{int. range}, and $ flags all follow a character sequence.
Sr.No Expression & Description
1
p+
It matches any string containing at least one p.
p*
It matches any string containing zero or more p's.
p?
It matches any string containing zero or more p's. This is just an alternative way to use
p*.
p{N}
It matches any string containing a sequence of N p's
p{2,3}
It matches any string containing a sequence of two or three p's.
p{2, }
It matches any string containing a sequence of at least two p's.
p$
^p
It matches any string with p at the beginning of it.
Examples
p.p
It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$
It matches any string containing exactly two characters.
<b>(.*)</b>
It matches any string enclosed within <b> and </b>.
p(hp)*
It matches any string containing a p followed by zero or more instances of the sequence php.
[[:digit:]]
It matches any string containing numerical digits 0 through 9.
[[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
[[:space:]]
It matches any string containing a space.
ereg()
The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces pattern with
replacement if found.
eregi()
The eregi() function searches throughout a string specified by pattern for a string specified by
string. The search is not case sensitive.
eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the search for
pattern in string is not case sensitive.
split()
The split() function will divide a string into various elements, the boundaries of each element
based on the occurrence of pattern in string.
spliti()
The spliti() function operates exactly in the same manner as its sibling split(), except that it is
not case sensitive.
sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting each character
in the input parameter string into a bracketed expression containing two characters.
The POSIX syntax can be used almost interchangeably with the Perl-style regular
expression functions.
Lets give explanation for few concepts being used in PERL regular expressions
Meta characters
A meta character is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
For instance, we can search for large money sums using the '\d' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character.
Following is the list of meta characters which can be used in PERL Style Regular Expressions.
Character
Description
a single character
\s
\S
non-whitespace character
\d
a digit (0-9)
\D
a non-digit
\w
\W
a non-word character
[aeiou]
[^aeiou]
ModifierDescription
i
cg
Sr.No
preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and
false otherwise.
preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions
can be used in the pattern and replacement input parameters.
preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are
accepted as input parameters for pattern.
preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.
preg_ quote()