Você está na página 1de 56

Working with Strings, Dates

and Time

Prepared by: Jerick Carlo Almeda


No matter how rich web content becomes,
HTML lies behind it all, pushing string-based
content out to web browsers. It is no
accident, then, that PHP provides many
functions with which you can format and
manipulate strings.

2
Prepared by: Jerick Carlo Almeda *
Similarly, dates and times are so much a
part of everyday life that it becomes easy to
use them without thinking. However,
because the quirks of the Gregorian
calendar can be difficult to work with, PHP
provides powerful tools that make date
manipulation an easy task.

Prepared by: Jerick Carlo Almeda *


In this lesson you will learn
How to format strings How to remove white
How to determine the space from the
length of a string beginning or end of a
How to find a string
substring within a How to replace
string substrings
How to break a string
down into component How to change the
parts case of a string

Prepared by: Jerick Carlo Almeda *


In this lesson you will learn
How to acquire the current date and time
How to get information about a date and time
How to format date and time information
How to test dates for validity
How to set dates and times

Prepared by: Jerick Carlo Almeda *


Investigating Strings in PHP

Prepared by: Jerick Carlo Almeda


You do not always know everything about
the data you are working with. Strings can
arrive from many sources, including user
input, databases, files, and web pages.
Before you begin to work with data from
an external source, you often will need to
find out more about the data. PHP
provides many functions that enable you
to acquire information about strings.

Prepared by: Jerick Carlo Almeda *


A Note About Indexing Strings
We will frequently use the word index in
relation to strings. You will have come
across this word in the context of arrays
In fact, strings and arrays are not as
different as you might imagine.

Prepared by: Jerick Carlo Almeda *


You can think of a string as an array of characters,
thus you can access the individual characters of a
string as if they were elements of an array:
<?php
$test = "phpcoder";
echo $test[0]; // prints "p"
echo $test[4]; // prints "o"
?>

It is important to remember that when we talk


about the position or index of a character within a
string, the characters, just like array elements,
have a starting index value of 0, not 1.
Prepared by: Jerick Carlo Almeda *
Finding the Length of a String with strlen()
• You can use the built-in strlen()
function to determine the length of a string.
• This function requires a string as its
argument and returns an integer
representing the number of characters in
the string you have passed to it

Prepared by: Jerick Carlo Almeda *


strlen() might be used to check the length of user input,
as in the following fragment, which tests a membership
code to ensure that it is exactly four digits long:

<?php if (strlen($membership) == 4) {
echo "<p>Thank you!</p>";
} else { echo "<p>Your membership number must have
4 digits.</p>";
} ?>

The user is thanked for his input only if the $membership


variable holds a string that is exactly four characters long.
Otherwise, an error message is presented.

Prepared by: Jerick Carlo Almeda *


Finding a Substring Within a String with strstr()

You can use the strstr() function to test


whether a string exists within another
string.
This function requires two arguments: the
source string and the substring you want
to find within it. The function returns false
if the substring cannot be found; otherwise,
it returns the portion of the source string,
beginning with the substring.
Prepared by: Jerick Carlo Almeda *
For the following example, imagine that we
want to treat membership codes that contain
the string AB differently from those that do
not:

<?php
$membership = "pAB7";
if (strstr($membership, "AB")) {
echo "<p>Your membership expires soon!</p>";
} else {
echo "<p>Thank you!</p>";
}
?>

Prepared by: Jerick Carlo Almeda *


Because the value of the $membership variable
contains the substring AB, the strstr() function
returns the string AB7. The function resolves to
true when tested, so we print the appropriate
message, "Your membership expires soon!". But
what happens if we search for "pab7"? Because
strstr() is case sensitive, AB will not be found. The
if statement's original test will fail, and the default
message will be printed to the browser ("Thank
you!"). If we want to search for either AB or ab
within the string, we must use strstr() in place of
substr(); the function is used in exactly the same
way, but its search is not case sensitive.
Prepared by: Jerick Carlo Almeda *
Finding the Position of a Substring with strpos()
The strpos() function tells you whether a
string exists within a larger string as well
as where it is found.
The strpos() function requires two
arguments: the source string and the
substring you are seeking.
The function also accepts an optional third
argument, an integer representing the
index from which you want to start
searching.
Prepared by: Jerick Carlo Almeda *
If the substring does not exist, strpos() returns
false; otherwise, it returns the index at which the
substring begins. The following fragment uses
strpos() to ensure that a string begins with the
string mz:

<?php
$membership = "mz00xyz";
if (strpos($membership, "mz") === 0) {
echo "Hello mz!";
} ?>

Prepared by: Jerick Carlo Almeda *


Although the strpos() function finds mz in
our string, it finds it at the first element the
0 position.
Returning zero will resolve to false in our if
condition test. To work around this, we use
the equivalence operator ===, which
returns true if the left- and right-hand
operands are equivalent and of the same
type, as they are in this case.

Prepared by: Jerick Carlo Almeda *


Extracting Part of a String with
substr()
The substr() function returns a string
based on the start index and length of the
characters you are looking for.
This function requires two arguments: a
source string and the starting index. Using
these arguments, the function returns all
the characters from the starting index to
the end of the string you are searching.
Prepared by: Jerick Carlo Almeda *
You can also (optionally) provide a third
argument an integer representing the length
of the string you want returned. If this third
argument is present, substr() returns only
that number of characters, from the start
index onward.

Prepared by: Jerick Carlo Almeda *


<?php
$test = "phpcoder";
echo substr($test,3)."<br/>"; //
prints "coder"
echo substr($test,3,2)."<br/>"; //
prints "co"
?>

Prepared by: Jerick Carlo Almeda *


If you pass substr() a negative number as its second (starting index)
argument, it will count from the end rather than the beginning of the
string. The following fragment writes a specific message to people who
have submitted an email address ending in .fr:

<?php
$test = "pierre@wanadoo.fr";
if ($test = substr($test, -3) == ".fr") {
echo "<p>Bonjour! Nous avons des prix spéciaux de
vous.</p>";
} else {
echo "<p>Welcome to our store.</p>";
}
?>

Prepared by: Jerick Carlo Almeda *


Manipulating Strings with PHP

Prepared by: Jerick Carlo Almeda


Cleaning Up a String with trim(), ltrim(), and
strip_tags()
When you acquire text from user input or
an external file, you can't always be sure
that you haven't also picked up white
space at the beginning and end of your
data.
The trim() function shaves any white
space characters, including newlines, tabs,
and spaces, from both the start and end of
a string. It accepts the string to be
modified, returning the cleaned-up version.
Prepared by: Jerick Carlo Almeda *
<?php
$text = "\t\tlots of room to breathe ";
echo "<pre>$text</pre>";
// prints " lots of room to breathe
";
$text = trim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe";
?>

Prepared by: Jerick Carlo Almeda *


You can use PHP's rtrim() function exactly
the same as you would use trim(). Only
white space at the end of the string
argument will be removed, however:

Prepared by: Jerick Carlo Almeda *


<?php
$text = "\t\tlots of room to breathe ";
echo "<pre>$text</pre>";
// prints " lots of room to breathe
";
$text = rtrim($text);
echo "<pre>$text</pre>";
// prints " lots of room to breathe";
?>

Prepared by: Jerick Carlo Almeda *


PHP provides the ltrim() function to strip
white space only from the beginning of a
string. Once again, this is called with the
string you want to transform and returns a
new string, shorn of tabs, newlines, and
spaces:

Prepared by: Jerick Carlo Almeda *


<?php
$text = "\t\tlots of room to breathe ";
echo "<pre>$text</pre>";
// prints " lots of room to breathe
";
$text = ltrim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe ";
?>

Prepared by: Jerick Carlo Almeda *


PHP provides the strip_tags() function
for this purpose. The strip_tags()
function accepts two arguments: the text to
transform and an optional set of HTML tags
that strip_tags() can leave in place. The
tags in this list should not be separated by
any characters.

Prepared by: Jerick Carlo Almeda *


<?php
$string = "<p>\"I <i>simply</i> will not
have it,\" <br/>said Mr Dean.</p>
<p><b>The end.</b></p>";
echo strip_tags($string, "<br/><p>");
?>

Prepared by: Jerick Carlo Almeda *


The output of this snippet is
"I simply will not have it,"
said Mr Dean.

The end.

Prepared by: Jerick Carlo Almeda *


Replacing a Portion of a String Using
substr_replace()
The substr_replace() function works
similarly to the substr() function, except it
allows you to replace the portion of the
string that you extract.

Prepared by: Jerick Carlo Almeda *


The function requires three arguments:
1. the string you are transforming
2. the text you want to add to it
3. and the starting index
• It also accepts an optional length
argument
• The substr_replace() function finds the
portion of a string specified by the starting
index and length arguments, replaces this
portion with the string provided, and
returns the entire transformed string.
Prepared by: Jerick Carlo Almeda *
In the following code fragment used to renew a
user's membership code, we change its second
two characters:

<?php
$membership = "mz05xyz";
$membership = substr_replace($membership,
"06", 2, 2);
echo "New membership number: $membership";
// prints "New membership number:
mz06xyz"
?>

Prepared by: Jerick Carlo Almeda *


Replacing Substrings Using
str_replace()
The str_replace() function is used to
replace all instances of a given string
within another string. It requires three
arguments: a search string, the
replacement string, and the master string.
The function returns the transformed string.

Prepared by: Jerick Carlo Almeda *


The following example uses str_replace()
to change all references from 2005 to 2006
within a master string:

<?php
$string = "<h1>The 2005 Guide to All
Things Good in the World</h1>";
$string .= "<p>Site contents copyright
2005.</p>";
echo str_replace("2005","2006",$string);
?>

Prepared by: Jerick Carlo Almeda *


The str_replace() function accepts arrays
as well as strings for all of its arguments.
This allows us to perform multiple search
and replace operations on a subject string,
and even on more than one subject string.
Take the following sample code in the next
slide.

Prepared by: Jerick Carlo Almeda *


<?php
$source = array(
"The package which is at version 4.2 was
released in 2005.",
"The year 2005 was an excellent time for
PointyThing 4.2!");
$search = array("4.2", "2005");
$replace = array("5.3", "2006");
$source = str_replace($search, $replace,
$source);
foreach($source as $str) {
echo "$str<br>";
}
?>
Prepared by: Jerick Carlo Almeda *
Output
The package which is at version 5.3 was
released in 2006.
The year 2006 was an excellent time for
PointyThing 5.3!

Prepared by: Jerick Carlo Almeda *


Converting Case
PHP provides several functions that allow
you to convert the case of a string.
Changing case is often useful for string
comparisons.
Cases in PHP will be shown in the next
slides.

Prepared by: Jerick Carlo Almeda *


strtoupper() – uppercase version of a
string.
strtolower() – lowercase version of a
string
ucwords() – first letter of every word in a
string uppercase
ucfirst() – capitalizes the first letter of
a string

Prepared by: Jerick Carlo Almeda *


Breaking Strings into Arrays with
explode()
explode() breaks up a string into an array, which
you can then store, sort, or examine as you want.
The explode() function requires two arguments:
the delimiter string that you want to use to break
up the source string and the source string itself.
The function optionally accepts a third argument,
which determines the maximum number of
pieces the string can be broken into.

Prepared by: Jerick Carlo Almeda *


<?php
$start_date = "2006-02-19";
$date_array = explode("-", $start_date);
// $date_array[0] == "2006"
// $date_array[1] == "02"
// $date_array[2] == "19"
echo $date_array[0]."-".$date_array[1]."-
".$date_array[2];
//prints 2006-02-19
?>

Prepared by: Jerick Carlo Almeda *


Using Date and Time
Functions in PHP

Prepared by: Jerick Carlo Almeda


The following sections introduce you to the
date- and time-related functions specifically
in PHP. Try out each listing for yourself to
see how simple and powerful these
functions can be.

Prepared by: Jerick Carlo Almeda *


Getting the Date with time()
PHP's time() function gives you all the
information you need about the current date
and time. It requires no arguments and
returns an integer. For us humans, the
returned number is a little hard on the eyes,
but it's extremely useful nonetheless.

Prepared by: Jerick Carlo Almeda *


echo time();
// sample output: 1141137255
// this represents February 28,
2006 at 06:33AM
The integer returned by time() represents
the number of seconds elapsed since
midnight GMT on January 1, 1970. This
moment is known as the UNIX epoch, and
the number of seconds that have elapsed
since then is referred to as a time stamp.
Prepared by: Jerick Carlo Almeda *
Converting a Time Stamp with getdate()
Now that you have a time stamp to work
with, you must convert it before you
present it to the user. getdate() optionally
accepts a time stamp and returns an
associative array containing information
about the date.

Prepared by: Jerick Carlo Almeda *


Key Description Example
seconds Seconds past the minute 43
(059)
minutes Minutes past the hour (059) 30
hours Hours of the day (023) 8
mday Day of the month (131) 9
wday Day of the week (06) 1
mon Month of the year (112) 8
year Year (4 digits) 2004
yday Day of the year (0365) 221
weekday Day of the week (name) Monday
month Month of the year (name) August
0 Time stamp 1092065443
Prepared by: Jerick Carlo Almeda *
Prepared by: Jerick Carlo Almeda *
Acquiring Date Information with
<?php
getdate()
$date_array = getdate(); // no argument passed so today's
date will be used
foreach ($date_array as $key => $val) {
echo "$key = $val<br>";
}
?>
<hr/>
<?php echo "<p>Today's date:
".$date_array['mon']."/".$date_array['mday']."/".
$date_array['year']."</p>";
?>

Prepared by: Jerick Carlo Almeda *


Converting a Time Stamp with
date()
You can use geTDate() when you want to work
with the elements that it outputs. Sometimes,
though, you want to display the date as a string.
The date() function returns a formatted string
that represents a date. You can exercise an
enormous amount of control over the format that
date() returns with a string argument that you
must pass to it. In addition to the format string,
date() optionally accepts a time stamp.

Prepared by: Jerick Carlo Almeda *


Format Description Example
a am or pm (lowercase) am
A AM or PM (uppercase) AM
d Day of month (number with 28
leading zeroes)
D Day of week (three letters) Tue
e Timezone identifier America/Los_Angeles
F Month name February
h Hour (12-hour 06
formatleading zeroes)
H Hour (24-hour 06
formatleading zeroes)
g Hour (12-hour formatno 6
leading zeroes)
Prepared by: Jerick Carlo Almeda *
G Hour (24-hour formatno 6
leading zeroes)
i Minutes 45
j Day of the month (no 28
leading zeroes)
l Day of the week (name) Tuesday
L Leap year (1 for yes, 0 for no) 0

m Month of year 2
(numberleading zeroes)
M Month of year (three letters) Feb
n Month of year (numberno 2
leading zeroes)

Prepared by: Jerick Carlo Almeda *


s Seconds of hour 26
S Ordinal suffix for the day of th
the month
r Full date standardized to Tue, 28 Feb 2006 06:45:26
RFC 822
(http://www.faqs.org/rfcs/rf -0800
c822.html)
U Time stamp 1141137926
y Year (two digits) 06
Y Year (four digits) 2006
z Day of year (0365) 28
Z Offset in seconds from GMT -28800

Prepared by: Jerick Carlo Almeda *


Formatting a Date with date()
<?php
$time = time(); //stores the exact
timestamp to use in this script
echo date("m/d/y G:i:s e", $time);
echo "<br/>";
echo "Today is ";
echo date("jS \o\f F Y, \a\\t g:ia
\i\\n e", $time);
?>
Prepared by: Jerick Carlo Almeda *

Você também pode gostar