Baixe String Manipulation and Regular Expressions in PHP: Functions and Examples e outras Notas de estudo em PDF para Informática, somente na Docsity!
String Manipulation and Regular
Expressions
In many applications you will need to do some kind of manipulation or parsing of strings. Whether you
are attempting to validate user data or extract data from text files, you need to know how to handle
strings. In this chapter we will take a look at some of PHP's string functions, and then explore and employ
regular expressions.
Basic String Functions
PHP includes dozens of functions for handling and processing strings. Some of the most common ones
are described below. A full listing can be found in Appendix A.
substr()
string substr (string source , int begin , int [ length ]);
The substr() function returns a part of a string. It receives three arguments (two required and one
optional). The first argument is the source string to be parsed. The second argument is the position at
which to begin the return string, where the first character's position is counted as zero. Therefore:
echo (substr("Christopher", 1));
will print hristopher. If the second argument is negative, substr() will count backwards from the
end of the source string:
echo (substr("Christopher", -2));
will print er. This basically says "Return the piece of the string beginning at the second-to-last
character". The third argument is optional. It is an integer that specifies the length of the substring to be
returned.
echo (substr("Christopher", -5, 3)); // Prints 'oph'
The code above returns a 3-character string beginning with the fifth-from-last character of the source
string. If a negative length is specified, the returned string will end that many characters from the end of
the source. Here are a few more examples:
// The string beginning at the 3rd-from-last echo (substr("Christopher", -3)); // Prints 'her'
// The 3rd, 4th, and 5th chars echo (substr("Christopher", 2, 3)); // Prints 'ris'
// From 3rd char to 3rd-from-last echo (substr("Christopher", 2, -3)); // Prints 'ristop'
// From 6th-from-last to 3rd-from-last echo (substr("Christopher", -6, -3)); // Prints 'top'
// A negative string! echo (substr("Christopher", 7, -8)); // Prints ''
trim()
Useful for "cleaning up" user input, trim() simply strips the whitespace characters (spaces, tabs,
newlines) from the beginning and end of a string and returns the "trimmed" string:
echo (trim(" sample string ")); // prints 'sample string'
If you wish to only trim the beginning of the string, use ltrim() (left trim). To trim only the end of a
string, use chop().
chr()
chr() receives an integer that represents an ASCII code, and returns the corresponding character.
echo (chr(34)); // Prints a quotation mark "
This is equivalent to:
A conversion specification begins with a % and consists of up to five specifiers (most of which are
optional). They are (from left-to-right):
1. An optional padding specifier. This is a component that indicates what character should be used
to fill out the result string to the desired size. By default, the padding specifier is a space. With
numbers, it is common to use zeroes as a padding specifier. To do so, just type a zero as the
padding specifier in the format string. If you want a padding specifier other than space or zero,
place a single quote before the character in the format string. For example, to fill out a string
with periods, type '. as the padding specifier component in the format string.
2. An optional alignment specifier. To make the string left-justified, include a hyphen (-) as the
alignment specifier. By default, strings are right-justified.
3. An optional minimum width specifier. This is simply an integer that indicates the minimum
number of characters the string should be. If you specify a width of 6 , and the source string is
only three characters wide, the rest of the string will be padded with the character indicated by
the padding specifier. Note that for floating point numbers, the minimum width specifier
determines the number of characters to the left of the decimal point.
4. An optional precision specifier. For floating point numbers (i.e. doubles), this number indicates
how many digits to display after the decimal point. For strings, it indicates the maximum length
of the string. In either case, the precision specifier appears after a decimal point. For all other
data types (other than double or string) the precision specifier does nothing.
5. A required type specifier. The type specifier indicates the type of data being represented. It can
be one of the following values:
� d - Decimal integer.
� b - Binary integer.
� o - Octal integer.
� x - Hexadecimal integer (with lowercase letters).
� X - Hexadecimal integer (with uppercase letters).
� c - Character whose ASCII code is integer value of the argument.
� f - Double (Floating-point number).
� e - Double, using exponential notation.
� s - String.
� % - A literal percent sign. This does not require a matching argument.
Unlike other languages, PHP does not use E, g, G or u type specifiers.
In our example above, %.2f uses the default values of the padding, alignment, and minimum width
specifiers. It explicitly specifies that the value should be represented as a double (f) with two digits after
the decimal point (.2).
As mentioned above, it is also possible to include ordinary characters in the format string that are to be
printed literally. Instead of 20.00, suppose we would like to print $20.00. We can do so simply by
adding a $ before the argument:
$dollars = 20; printf ("$%.2f", $dollars); // prints: $20.
Lets examine a more complex example: In a table of contents, one usually lists the name of a chapter on
the left, and a page number on the right. Often, the rest of the line in between is filled with dots to help
the eye navigate the space between the left and right columns. This can be achieved by left-justifying the
chapter name and using a period as a padding specifier. In this case, our printf() statement will have
three arguments after the format string: one for the chapter name, one for the page number, and one for
the newline tag. Note that in a browser a monospace font is needed to ensure proper alignment, since we
are using printf() instead of a table.
// Set variables: $ch3_title = "Bicycle Safety"; $ch3_pg = 83;
$ch4_title = "Repairs and Maintenance"; $ch4_pg = 115;
// Print the TOC printf ("%'.-40.40s%'.3d%s", $ch3_title, $ch3_pg, "
\n"); printf ("%'.-40.40s%'.3d%s", $ch4_title, $ch4_pg, "
\n");
This code will print:
Bicycle Safety........................... Repairs and Maintenance.................
Let us examine this format string (%'.-40.40s%'.3d%s) closely. It consists of three directives. The
first, %'.-40.40s, corresponds to the chapter argument. The padding specifier is '., indicating that
periods should be used. The hyphen specifies left-justification. The minimum and maximum sizes are set
to forty (40.40), and the s clarifies that the value is to be treated as a string.
The second directive, %'.3d, corresponds to the page number argument. It produces a right-justified,
period-padded ('.) decimal integer d with a minimum width of three characters. The third directive, %s,
simply treats
\n as a string.
number_format()
The printf() and sprintf() functions can produce sophisticated formatted output of strings and
numbers. If you only need simple formatting of numbers, you can use the mathematical function,
number_format():
string number_format (float num, int precision, string dec_point, string thousands_sep);
The function takes one, two, or four arguments. (Three arguments will result in an error.) If only the first
argument is used, num is depicted as an integer with commas separating the thousands:
$num = 123456789.1234567;
^once
This pattern includes the special character ^, which indicates that the pattern should only match for
strings that begin with the string "once"; so the string "once upon a time" would match this pattern, but
the string "There once was a man from Nantucket" would not. Just as the ^ character matches strings that
begin with the pattern, the $ character is used to match strings that end with the given pattern.
bucket$
would match the string "Who kept all of his cash in a bucket", but it would not match "buckets". ^ and $
can be used together to match exact strings (with no leading or trailing characters not in the pattern). For
example:
^bucket$
matches only the string "bucket". If the pattern does not contain ^ or $, then the match will return true if
the pattern is found anywhere in the source string. For the string:
There once was a man from Nantucket Who kept all of his cash in a bucket
the pattern
once
would result in a match
The letters in the pattern ("o", "n", "c", and "e") are literal characters. Letters and numbers all match
themselves literally in the source string. For slightly more complex characters, such as punctuation and
whitespace characters, we use an escape sequence. Escape sequences all begin with a backslash (). For a
tab character, the sequence is \t. So if we want to detect whether a string begins with a tab, we use the
pattern:
^\t
This would match the strings:
But his daughter, named Nan Ran away with a man
since both of these lines begin with tabs. Similarly, \n represents a newline character, \f represents a
form feed, and \r represents a carriage return. For most punctuation marks, you can simply escape them
with a . Therefore, a backslash itself would be represented as \, a literal. would be represented as .,
and so on. A full list of these escaped characters can be found in Appendix E.
Character Classes
In Internet applications, regular expressions are especially useful for validating user input. You want to
make sure that when a user submits a form, his or her phone number, address, e-mail address, credit card
number, etc. all make reasonable sense. Obviously, you could not do this by literally matching individual
words. (To do that, you would have to test for all possible phone numbers, all possible credit card
numbers, and so on.)
We need a way to more loosely describe the values that we are trying to match, and character classes
provide a way to do that. To create a character class that matches any one vowel, we place all vowels in
square brackets:
[AaEeIiOoUu]
This will return true if the character being considered can be found in this "class", hence the name,
character class. We can also use a hyphen to represent a range of characters:
[a-z] // Match any lowercase letter [A-Z] // Match any uppercase letter [a-zA-Z] // Match any letter [0-9] // Match any digit [0-9.-] // Match any digit, dot, or minus sign [ \f\r\t\n] // Match any whitespace character
Be aware that each of these classes is used to match one character. This is an important distinction. If you
were attempting to match a string composed of one lowercase letter and one digit only, such as "a2", "t6",
or "g7"; but not "ab2", "r2d2", or "b52", you could use the following pattern:
^[a-z][0-9]$
Even though [a-z] represents a range of twenty-six characters, the character class itself is used to match
only the first character in the string being tested. (Remember that ^ tells PHP to look only at the
beginning of the string. The next character class, [0-9] will attempt to match the second character of the
string, and the $ matches the end of the string, thereby disallowing a third character.
Weve learned that the carat (^) matches the beginning of a string, but it can also have a second meaning.
When used immediately inside the brackets of a character class, it means "not" or "exclude". This can be
used to "forbid" characters. Suppose we wanted to relax the rule above. Instead of requiring only a
lowercase letter and a digit, we wish to allow the first character to be any non-digit character:
^[^0-9][0-9]$
This will match strings such as "&5", "g7" and "-2"; but not " 12 " or " 66 ". Here are afew more examples
of patterns that exclude certain characters using ^:
[^a-z] // Any character that is not a lowercase letter [^\/^] // Any character except (), (/), or (^) [^"'] // Any character except (") or (')
The special character "." is used in regular expressions to represent any non-newline character. Therefore
the pattern ^.5$ will match any two-character string that ends in five and begins with any character
(other than newline). The pattern. by itself will match any string at all, unless it is empty or composed
entirely of newline characters.
Several common character classes are "built in" to PHP regular expressions. Some of them are listed
below:
"match the previous character if it occurs at least x times, but no more than y times". From this we can
derive patterns representing words and numbers:
^[a-zA-Z0-9_]{1,}$ // match any word of at least one letter, number or _ ^[0-9]{1,}$ // match any positive integer number ^-{0,1}[0-9]{1,}$ // match any integer number ^-{0,1}[0-9]{0,}.{0,1}[0-9]{0,}$ // match any double
Well, that last one is a bit unwieldy, isn't it. Here's the translation: match a string that begins (^) with an
optional minus sign (-{0,1}), followed by zero or more digits ([0-9]{0,}), followed by an optional
decimal point (.{0,1}), followed again by zero or more digits ([0-9]{0,}) and nothing else ($).
Whew! You'll be pleased to know that there are a few more shortcuts that we can take.
The special character? is equivalent to {0,1}. In other words it means, "zero or one of the previous
character" or "the previous character is optional". That reduces our pattern to ^-?[0-9]{0,}.?[0-
9]{0,}$. The special character * is equivalent to {0,} -- "zero or more of the previous character".
Finally, the special character + is equivalent to {1,}, giving it the meaning "one or more of the previous
character". Therefore our examples above could be written:
^[a-zA-Z0-9_]+$ // match any word of at least one letter, number or _ ^[0-9]+$ // match any positive integer number ^-?[0-9]+$ // match any integer number ^-?[0-9].?[0-9]$ // match any double
While this doesn't technically alter the complexity of the regular expressions, it does make them a little
easier to read. The astute will notice that our pattern for matching a double is not perfect, since the string
"-." would result in a match. Programmers often take a "close enough" attitude when using form
validation. You will have to evaluate for yourself how much you can afford to do this in your own
applications.
Consider what the consequences would be if the user enters a value that can "slip by" your validation
routine, such as "-." in the example above. Will this value then be used for calculations? If so, this could
result in an error. Will it just be stored in a database and displayed back to the user later? That might have
less serious consequences. How likely is it that such a value will be submitted? I always prefer to err on
the side of caution.
Of course, for testing a double, we do not need regular expressions at all, since PHP provides the
is_double() and is_int() functions. In other cases, you may have no simple alternative; you will
have to perfect your regular expression to match valid values and only valid values. Alternation , which is
discussed in the next section, provides more flexibility for solving some of these problems. In the mean
time, let's take a look at another "close enough" solution to a problem. Do you remember this regular
expression?:
^.+@.+\..+$
This is the little stunner that I introduced at the beginning of the section on regular expressions. It is used
to determine whether a string is an e-mail address. As we well know by now, ^ begins testing from the
very beginning of the string, disallowing any leading characters. The characters .+ mean "one or more of
any character except newline". Next we have a literal @ sign (@), then again "one or more of any character
except newline" (.+), followed by a literal dot (\.), followed again by .+, and finally, a $ signifying no
trailing characters. So this pattern loosely translates to:
What makes this "close enough" as opposed to "perfect"? For the most part, it's those dots. "Any
character except newline" is a pretty wide net to cast. It includes tabs and all kinds of punctuation. This
will even match the following string:
Can you see why? The first @ matches something1. The second @ serves as the literal @. The first dot
matches something2. The second dot serves as the literal dot, and the final dot matches something3.
So why do I use this regular expression to test for valid e-mail addresses? Because generally, it is close
enough. Since some punctuation marks are legal in email addresses, we would have to create very
complex character classes to weed out allowable characters and sequences from illegal characters and
sequences; and since the consequences are not grave if someone slips by an invalid email address, we
choose not to pursue the matter further.
Alternation and Parentheses
In regular expressions, the special character | behaves much like a logical OR operator. The pattern a|c
is equivalent to [ac]. For single characters, it is simpler to continue using character classes. But |
allows alternation between entire words. If we were testing for valid towns in New York, we could use
the pattern Manhasset|Sherburne|Newcomb. This regular expression would return true if the string
equals "Manhasset" or "Sherburne" or "Newcomb".
Parentheses give us a way to group sequences. Let's revisit the limerick from earlier in the chapter:
There once was a man from Nantucket Who kept all of his cash in a bucket But his daughter, named Nan Ran away with a man And as for the bucket, Nantucket
The pattern bucket+ would match the strings "bucket", "buckett", "buckettt", etc. The + only
applies to the "t". With parentheses, we can apply a multiplier to more than one character:
(bucket)+
This pattern matches "bucket", "bucketbucket", "bucketbucketbucket", etc. When used in
combination with other special characters, the parentheses offer a lot of flexibility:
(Nant|b)ucket // Matches "Nantucket" or "bucket" Nan$ // Matches "Nan" at the end of a string daughter|Nan$ // Matches "daughter" anywhere, or"Nan" at the end of a string (daughter|Nan)$ // Matches either "daughter" at the end of a string, or "Nan" // at the end of a string [xy]|z // Equivalent to [xyz] ([wx])([yz]) // Matches "wy", "wz", "xy", or "xz"
if (ereg("^(.+)@(.+)\.(.+)$", $email, $arr)) { echo ("E-mail address is valid.
\n". "E-mail address: $arr[0]
\n". "Username: $arr[1]
\n". "Domain name: $arr[2]
\n". "Top-level domain name: $arr[3]
\n" ); } else { echo ("Invalid e-mail address.
\n"); }
eregi() behaves identically to ereg(), except it ignores case distinctions when matching letters.
// Gratuitous limerick:
// But he followed the pair to Pawtucket // The man and the girl with the bucket // And he said to the man // He was welcome to Nan // But as for the bucket, Pawtucket
ereg("paw", "But he followed the pair to Pawtucket") // returns false
eregi("paw", "But he followed the pair to Pawtucket") // returns true
ereg_replace() and eregi_replace()
string ereg_replace(string pattern, string replacement, string string );
ereg_replace() searches string for the given pattern and replaces all occurrences with
replacement. If a replacement took place, it returns the modified string; otherwise, it returns the
original string:
$str = "Then the pair followed Pa to Manhasset"; $pat = "followed"; $repl = "FOLLOWED"; echo (ereg_replace($pat, $repl, $str));
prints:
Then the pair FOLLOWED Pa to Manhasset
Like ereg(), ereg_replace() also allows special treatment of parenthesized substrings. For each
left parenthesis in the pattern, ereg_replace() will "remember" the value stored in that pair of
parentheses, and represent it with a digit (1 to 9). You can then refer to that value in the replacement
string by including two backslashes and the digit. For example:
$str = "Where he still held the cash as an asset";
$pat = "c(as)h"; $repl = "C\1H"; echo (ereg_replace($pat, $repl, $str));
This prints:
Where he still held the CasH as an asset
The "as" is stored as \1, and can thus be referenced in the replacement string. \0 refers to the entire
source string. If there were a second set of parentheses, it could be referenced by \2:
$str = " But Nan and the man"; $pat = "(N(an))"; $repl = "\1-\2"; echo (ereg_replace($pat, $repl, $str));
This prints:
But Nan-an and the man
In this example, \1 equals "Nan", and \2 equals "an". Up to nine values may be stored in this way.
As you probably guessed, eregi_replace() behaves like ereg_replace(), but ignores case
distinctions:
$str = " Stole the money and ran"; $pat = "MONEY"; $repl = "cash";
echo (ereg_replace($pat, $repl, $str)); // prints " Stole the money and ran"
echo (eregi_replace($pat, $repl, $str)); // prints " Stole the cash and ran"
split()
array split (string pattern, string string, int [limit]);
The split() function returns an array of strings. The pattern is used as a delimiter; it splits the string
into substrings and saves each substring as an element of the returned array. split() returns false if an
error occurs.
In the example below, we use a space as the delimiter, thereby breaking the sentence into the individual
words:
$str = "And as for the bucket, Manhasset"; $pat = " "; $arr = split($pat, $str); echo ("$arr[0]; $arr[1]; $arr[2]; $arr[3]\n");