Date post: | 24-May-2015 |
Category: |
Education |
Upload: | henry-osborne |
View: | 327 times |
Download: | 0 times |
Strings and Patterns
String Basics
String Basics
hex and octal notation to display an asterisk:
echo "\x2a";
echo "\052";
Variable Interpolation
$who = "World";
echo "Hello $who\n"; // Shows "Hello World" followed by a newline
echo ’Hello $who\n’; // Shows "Hello $who\n"
Variable Interpolation, cont’d
$me = ’Davey’;
$names = array (’Smith’, ’Jones’, ’Jackson’);
echo "There cannot be more than two {$me}s!";
echo "Citation: {$names[1]}[1987]";
The Heredoc Syntax
Used to declare complex strings
Easier to declare strings that include many double-quote characters
$who = "World";
echo <<<TEXT
So I said, "Hello $who"
TEXT;
String Length
The strlen() function is used to determine the length, in bytes, of a string
binary-safe: all characters in the string are counted, regardless of their value
String Transform
The strtr() function can be used to translate certain characters of a string into other characters
// Single character version
echo strtr (’abc’, ’a’, ’1’); // Outputs 1bc
// Multiple-character version
$subst = array (
’1’ => ’one’,
’2’ => ’two’,
);
echo strtr (’123’, $subst); // Outputs onetwo3
Strings as Arrays
Individual characters of a string can be accessed as if they were members of an array
$string = ’abcdef’;
echo $string[1]; // Outputs ’b’
Note that string character indices are zero-based - meaning that the first character of an arbitrary string $s has an index of zero, and the last has an index of strlen($s)-1.
Comparing, Searching and Replacing Strings
String Comparison, cont’d
$string = ’123aa’;
if ($string == 123) {
// The string equals 123
}
String Comparison
$str = "Hello World";
if (strcmp($str, "hello world") === 0) {
// We won’t get here, because of case sensitivity
}
if (strcasecmp($str, "hello world") === 0) {
// We will get here, because strcasecmp()
// is case-insensitive
}
String Comparison, cont’d
$s1 = ’abcd1234’;
$s2 = ’abcd5678’;
// Compare the first four characters
echo strncasecmp ($s1, $s2, 4);
String Search
$haystack = "abcdefg";
$needle = ’abc’;
if (strpos ($haystack, $needle) !== false) {
echo ’Found’;
}
String Search, cont’d
$haystack = ’123456123456’;
$needle = ’123’;
echo strpos ($haystack, $needle); // outputs 0
echo strpos ($haystack, $needle, 1); // outputs 6
String Search, cont’d
$haystack = ’123456’;
$needle = ’34’;
echo strstr ($haystack, $needle); // outputs 3456
Note Well
In general, strstr() is slower than strpos()—therefore, you should use the latter if your only goal is to determine whether a certain needle occurs inside the haystack.
Also, note that you cannot force strstr() to start looking for the needle from a given location by passing a third parameter.
String Search, cont’d
// Case-insensitive search
echo stripos(’Hello World’, ’hello’); // outputs zero
echo stristr(’Hello My World’, ’my’); // outputs "My World"
// Reverse search
echo strrpos (’123123’, ’123’); // outputs 3
Matching Against a Mask
$string = ’133445abcdef’;
$mask = ’12345’;
echo strspn ($string, $mask); // Outputs 6
Note Well
The strcspn() function works just like strspn(), but uses a blacklist approach instead—that is, the mask is used to specify which characters are disallowed, and the function returns the length of the initial segment of the string that does not contain any of the characters from the mask.
Matching Against a Mask, cont’d
$string = ’1abc234’;
$mask = ’abc’;
echo strspn ($string, $mask, 1, 4);
Search and Replace Operations
echo str_replace("World", "Reader", "Hello World");
echo str_ireplace("world", "Reader", "Hello World");
Search and Replace, cont’d
echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "Hello World");
echo str_replace(array("Hello", "World"), "Bye", "Hello World");
Search and Replace, cont’d
echo substr_replace("Hello World", "Reader", 6);
echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8);
Search and Replace, cont’d
$user = “[email protected]";
$name = substr_replace($user, "", strpos($user, ’@’);
echo "Hello " . $name;
Extracting Substrings
$x = ’1234567’;
echo substr ($x, 0, 3); // outputs 123
echo substr ($x, 1, 1); // outputs 2
echo substr ($x, -2); // outputs 67
echo substr ($x, 1); // outputs 234567
echo substr ($x, -2, 1); // outputs 6
Formatting Strings
Formatting Numbers
// Shows 100,001
echo number_format("100000.698");
// Shows 100 000,698
echo number_format("100000.698", 3, ",", " ");
Formatting Currency Values
setlocale(LC_MONETARY, "en_US");
echo money_format(’%.2n’, "100000.698");//$100,000.70
setlocale(LC_MONETARY, "ja_JP.UTF-8");
echo money_format(’%.2n’, "100000.698");//¥100,000.70
Generic Formatting
If you are not handling numbers or currency values, you can use the printf() family of functions to perform arbitrary formatting of a value.
A formatting specifier always starts with a percent symbol and is followed by a type specification token: A sign specifier (a plus or minus symbol) to determine how signed numbers are to be
rendered
A padding specifier that indicates what character should be used to make up the required output length, should the input not be long enough on its own
An alignment specifier that indicates if the output should be left or right aligned
A numeric width specifier that indicates the minimum length of the output
A precision specifier that indicates how many decimal digits should be dis-played for floating-point numbers
Commonly Used Specifiers
b Output an integer as a Binary number.
c Output the character which has the input integer as its ASCII value.
d Output a signed decimal number
e Output a number using scientific notation (e.g., 3.8e+9)
u Output an unsigned decimal number
f Output a locale aware float number
F Output a non-locale aware float number
o Output a number using its Octal representation
s Output a string
x Output a number as hexadecimal with lowercase letters
X Output a number as hexadecimal with uppercase letters
Examples of printf() usage
$n = 123;
$f = 123.45;
$s = "A string";
printf ("%d", $n); // prints 123
printf ("%d", $f); // prints 123
// Prints "The string is A string"
printf ("The string is %s", $s);
// Example with precision
printf ("%3.3f", $f); // prints 123.450
// Complex formatting
function showError($msg, $line, $file)
{
return sprintf("An error occurred in %s on "line %d: %s", $file, $line, $msg);
}
showError ("Invalid deconfibulator", __LINE__, __FILE__);
Parsing Formatted Input
$data = ’123 456 789’;
$format = ’%d %d %d’;
var_dump (sscanf ($data, $format));
Strings and Patterns