Working with Strings, Dates and Time - Part 4 of Learning PHP

Rate article down Rate article up 0 subscribe to cyberstream photos rss feed
Download the Opera: a fast, efficient, feature-packed, secure, personalizable web browser. Today we are going to dive into PHP's huge function library and learn how to manipulate strings. Some are simple, like the strlen() function that we looked at in the last part of this series. However, some of PHP's functions support a complex matching pattern called Regular Expressions (commonly called "RegEx"). Although we won't look at those in this post, you get the idea—PHP has functions for whatever you want to do. I'll start by introducing you to some simple string manipulation functions.

Simple String Manipulation

Here are some simple functions that we'll look at first. If you want to find more out about the function, most of the function names should automatically link to their respective reference page in the PHP manual.
$text = ' HellO WorLd';

echo $text; // " HellO WorLd"

$text = trim($text);
echo $text; // now whitespace (spaces, tabs, etc.) is trimmed off both ends

echo strlen($text); // 12
echo strrev($text); // "dLroW OlleH" - reversed the string
echo lcfirst($text); // "hellO WorLd" - made the first letter lowercase
echo ucfirst($text); // "HellO WorLd" - no effect since the first letter is already uppercase

echo strtolower($text); // "hello world" - converts to lowercase

echo str_repeat($text, 3); //"HellO WorLdHellO WorLdHellO WorLd" - repeats the the inputted string the specified number of times, in this case, 3

str_word_count($text); // "2" - word count
These are just a handful of functions that you can use to manipulate strings. The real power of these functions comes when you combine them. I used random caps intentionally in the last example. Here's how we could combine two functions to create a properly capitalized name:
$myName = 'eLi MiTchElL';

$myName = strtolower($text); // now my name is "eli mitchell"
$myName = ucwords($text); // capitalize the first letter of each word

echo $myName; // "Eli Mitchell" 
This would do the same thing...
echo ucwords(strtolower('eLi MiTchElL')); 
...but the first example was more readable, and it is very important to maintain readability.

Replacing in Strings

It is very simple to replace anything in a string. The easiest function to use is str_replace(). It takes a minimum of three parameters. The first parameter specifies what to search for. If the string in the first parameter is found, then it is replaced with the string in the second argument. The third argument is the string—whether it is a raw string, variable or a function that returns a string—that will be operated on.
$year = date('Y'); // gets the current 4-digit year

$string = 'The current year is YEAR';
echo str_replace('YEAR', $year, $string); // "The current year is 2011" 
As you can see, this function is case-sensitive. There is a case-insensitive version of this function, though.
$year = date('Y'); // gets the current 4-digit year

$string = 'The current year is YEAR';
echo str_ireplace('YEAR', $year, $string); // "The current 2011 is 2011" 
As you can see, this can produce unexpected results. Both of these replacement functions have an optional fourth argument. It specifies how many replacements to perform.
$year = date('Y'); // gets the current 4-digit year

$string = 'year is the current year.';
$result = str_ireplace('year', $year, $string, 1); // only perform 1 replacement 

echo $result; // "2011 is the current year." 

Searching Strings

There is a wide variety of functions for searching strings. Here are a few of them:
$haystack = 'The quick fox jumped over the lazy dog.';
$needle = 'fox';

$position = strpos($haystack, $needle);

if ($position) {
   echo 'the $needle was found ' . $position . ' characters from the left';    
} else echo 'Could not find $needle in $haystack'; 
This will echo "the $needle was found 10 characters from the left". There's also a function for searching from the right (it will return the last occurrence of the "needle"). It is strrpos(). There are also case-insensitive alternatives for strpos and strrpos: stripos and strripos, respectively.

Substrings

You may be wondering what good the position of a string is for you. Well, for one, if this can be used to check if a phrase/letter/word exists in a string. There's a catch with these functions though. Consider this example:
$haystack = 'fox jumped over the lazy dog.';
$needle = 'fox';

$position = strpos($haystack, $needle);

if ($position) {
   echo 'the $needle was found ' . $position . ' characters from the left';    
} else echo 'Could not find $needle in $haystack'; 
The $position of 'fox' would be zero. Remember what zero evaluates to in Boolean? It evaluates to false. So $position is actually false, and it will echo, 'Could not find $needle in $haystack.' There is a simple workaround, however. Remember the identity operator (===)? It tests if the two values being compared are the same value and type. We will use the "not-identical" operator (!==) to check that $position is not boolean false, which is what these functions return when the $needle isn't found.
$haystack = 'fox jumped over the lazy dog.';
$needle = 'fox';

$position = strpos($haystack, $needle);

if ($position !== false) {
   echo 'the $needle was found ' . $position . ' characters from the left';    
} else echo 'Could not find $needle in $haystack'; 

Sub-Strings

Here's a practical use for strpos. We'll combine it with another function called substr(). Substr() extracts a specified section ("sub-string") from a longer string. It takes a minimum of two arguments. Here's the syntax:
substr(string, start[, opt length ])
If you only define the start parameter, then it will go from start position to the end. You can use negative numbers for "start". If start was -3, it would fetch the last three letters. If you did this: substr($string, -5, 2);, it would fetch the the first two letters from the last 5 letters of the string. As you can see, this is an extremely powerful function.

Practical Application

Say you've got a blog post. You want to extract a preview of the post to display on the blog page. However, you don't want the post preview to end in the middle of the word. We'll do it like this:
  1. Extract 150 words from the main post.
  2. Detect the position the last space (end of a word) in the extraction.
  3. Trim the string down to that position.
Let's translate this to PHP.
$post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc molestie cursus massa, sed tincidunt neque aliquam eu. Proin accumsan egestas auctor. Mauris facilisis metus in quam sollicitudin bibendum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla et arcu nunc. Aliquam gravida dignissim leo. Aenean nibh velit, laoreet ut pulvinar ac, consequat ac nunc. Phasellus condimentum neque quis nisl porta et venenatis enim iaculis. Vivamus tempor pulvinar mi id ullamcorper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla semper, lorem.";

$substr = substr($post, 0, 120); //start at position 0 and extract 120 letters
$last_space = strrpos($substr, ' '); //we are going to find the last space in $substr

$excerpt = substr($substr, 0, $last_space);
$final_excerpt = $excerpt . ' ...'; //append an ellipsis onto the excerpt 

Complex String Formatting

There is one last things I want to discuss in the topic of strings. PHP has a function called printf() for complex string formatting. The first argument is a string. You can format specifiers in the string. All format specifiers begin with the percent symbol (%). The first format specifier is then substituted with a variable from the second argument. For each formatting specifier, you must have a corresponding following parameter.
printf('The quick %s jumped over the lazy %s %d times.', 'fox', 'dog', 7); // "The quick brown fox jumped over the lazy dog 7 times"
%s represents a string. %d is the placeholder for a number.

Specifiers

There are 6 specifiers in the prinf format string.

Sign Specifier

By default, PHP only displays a sign in front of a number if the number is negative. However, you can force PHP to show a sign, whether the number is negative or positive.
printf('%+d', 4); // "+4" 

Padding Specifier

If you want the substituted text to fill a minimum area, you can pad characters with a specified character if they do not meet that minimum length. By default, it will pad with spaces.
printf("%10d", 3711); // "      3711" 
10 indicates how many spaces the string should be padded. You can change the padding character to a zero (0) by placing a zero before the padding specifier. If you want to pad with any other character, you must precede that character with a single-quote.
printf("%09s", 'string'); // "000string"
printf("Credit card #: %'*16d", 3177); //"Credit card #: ************3177" 

Alignment Specifier

When you pad with characters, they are by default aligned to the right. But you can left-align by simply adding a dash (-).
printf("%-10d", 3711); // "3711      "

Precision Specifier

The precision specifier can be used with floating-point numbers or strings. With strings (s), it defines the cutoff point. With floats, it specifies how many decimal digits should be displayed. The precision specifier is a period (.) optionally followed by a type specifier that indicates the cutoff point (for strings) or the number of decimal digits to be display (for floats).
printf("%.2f", 7); //"7.00" - display 2 decimal digits with the float
printf("%02.2f", 7); //"07.00" - display 2 decimal digits; pad the number with up to two 0s.
printf("%.10s", 'Hello World!'); //"Hello Worl" - displays 10 characters from the string
printf("%010.10s", 'Hello!'); //"0000Hello!" - cutoff point of 10 characters; pad up to 10 zeros

Type Specifiers

Type specifiers indicate what the argument's data should be treated like. Up to now, we've only been using s (string) and f (float). However, there are many more. You can see the full list here.

sprintf() or printf()?

Up until now, I've been using the printf() function. However, There is another variation called sprintf(). Printf directly outputs the result (prints it), however sprintf returns the result. For this reason, you will probably use sprintf more often. If don't know or forgot the difference between returning and printing, the section covering it is in the last chapter that covers functions.

Working with Dates and Times

Since we just finished the section on string formatting, let's look briefly at dates. A common way to display the current time on computers is with the UNIX Timestamp, referred to as epoch timestamp, or simply the timestamp. It is the number of seconds since January 1, 1970. This is how computers store their time. The function to get the current timestamp is [code]time()[/code]. The other function we want to look at is [code]date()[/code]. The first argument of date() is the format of the current time. Don't worry, it isn't as complicated as printf(). You can see a list of format specifiers here. Here's a common date format:
echo date('Y-m-d'); // "2011-03-07" 
You can combine time() and date() to format any timestamp: past, present or future. Date() accepts a second argument that is optional. It is the timestamp of the date that you want formatted. Here's how you could format the date of a day a week in advance:
$in_one_week = time() + (60 * 60 * 24 * 7); //remember, time() is the current timestamp, down to the second.

echo date('Y-m-d', $in_one_week); // "3-14-11" 
You can create the timestamp for a specified date with [code]mktime()[/code]. This is the syntax:
mktime (hour, minute, second, month, day, year, is_dst);
If you leave parameters empty in mktime(), they will automatically revert to the current value for that argument. There are many more date/time functions available. You can see the whole list here.

Conclusion

I hope you've learned a lot in this post. As you can see, PHP has many ways to handle strings. You may not understand these functions immediately, but understanding will come with time if you continue learning. If you have anything to add to my post or a question to ask, please drop a comment below. Stay tuned for PHP's control structures!

Posted March 4, 2011 at 6:17AM by Eli Mitchell in PHP, web, programming with 0 responses

Post a comment!

Name:
Your website: (optional)
E-mail:

Your comment: