PHP Strings and Patterns

34
Strings and Patterns

description

String manipulation is a very important skill for PHP developers.

Transcript of PHP Strings and Patterns

Page 1: PHP Strings and Patterns

Strings and Patterns

Page 2: PHP Strings and Patterns

String Basics

Page 3: PHP Strings and Patterns

String Basics

hex and octal notation to display an asterisk:

echo "\x2a";

echo "\052";

Page 4: PHP Strings and Patterns

Variable Interpolation

$who = "World";

echo "Hello $who\n"; // Shows "Hello World" followed by a newline

echo ’Hello $who\n’; // Shows "Hello $who\n"

Page 5: PHP Strings and Patterns

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]";

Page 6: PHP Strings and Patterns

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;

Page 7: PHP Strings and Patterns

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

Page 8: PHP Strings and Patterns

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

Page 9: PHP Strings and Patterns

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.

Page 10: PHP Strings and Patterns

Comparing, Searching and Replacing Strings

Page 11: PHP Strings and Patterns

String Comparison, cont’d

$string = ’123aa’;

if ($string == 123) {

// The string equals 123

}

Page 12: PHP Strings and Patterns

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

}

Page 13: PHP Strings and Patterns

String Comparison, cont’d

$s1 = ’abcd1234’;

$s2 = ’abcd5678’;

// Compare the first four characters

echo strncasecmp ($s1, $s2, 4);

Page 14: PHP Strings and Patterns

String Search

$haystack = "abcdefg";

$needle = ’abc’;

if (strpos ($haystack, $needle) !== false) {

echo ’Found’;

}

Page 15: PHP Strings and Patterns

String Search, cont’d

$haystack = ’123456123456’;

$needle = ’123’;

echo strpos ($haystack, $needle); // outputs 0

echo strpos ($haystack, $needle, 1); // outputs 6

Page 16: PHP Strings and Patterns

String Search, cont’d

$haystack = ’123456’;

$needle = ’34’;

echo strstr ($haystack, $needle); // outputs 3456

Page 17: PHP Strings and Patterns

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.

Page 18: PHP Strings and Patterns

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

Page 19: PHP Strings and Patterns

Matching Against a Mask

$string = ’133445abcdef’;

$mask = ’12345’;

echo strspn ($string, $mask); // Outputs 6

Page 20: PHP Strings and Patterns

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.

Page 21: PHP Strings and Patterns

Matching Against a Mask, cont’d

$string = ’1abc234’;

$mask = ’abc’;

echo strspn ($string, $mask, 1, 4);

Page 22: PHP Strings and Patterns

Search and Replace Operations

echo str_replace("World", "Reader", "Hello World");

echo str_ireplace("world", "Reader", "Hello World");

Page 23: PHP Strings and Patterns

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");

Page 24: PHP Strings and Patterns

Search and Replace, cont’d

echo substr_replace("Hello World", "Reader", 6);

echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8);

Page 25: PHP Strings and Patterns

Search and Replace, cont’d

$user = “[email protected]";

$name = substr_replace($user, "", strpos($user, ’@’);

echo "Hello " . $name;

Page 26: PHP Strings and Patterns

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

Page 27: PHP Strings and Patterns

Formatting Strings

Page 28: PHP Strings and Patterns

Formatting Numbers

// Shows 100,001

echo number_format("100000.698");

// Shows 100 000,698

echo number_format("100000.698", 3, ",", " ");

Page 29: PHP Strings and Patterns

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

Page 30: PHP Strings and Patterns

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

Page 31: PHP Strings and Patterns

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

Page 32: PHP Strings and Patterns

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__);

Page 33: PHP Strings and Patterns

Parsing Formatted Input

$data = ’123 456 789’;

$format = ’%d %d %d’;

var_dump (sscanf ($data, $format));

Page 34: PHP Strings and Patterns

Strings and Patterns