PHP Strings and Patterns

0 %
100 %
Information about PHP Strings and Patterns

Published on January 26, 2014

Author: sicarii_13



String manipulation is a very important skill for PHP developers.

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 $whon"; // Shows "Hello World" followed by a newline echo ’Hello $whon’; // Shows "Hello $whon"

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 = “"; $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 floatingpoint 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

Add a comment

Related presentations

Related pages Stringing Patterns

Strings: 3147: Testers: 17758: 129 users online. User: Guest : ... Stringing Patterns: The stringing pattern database - from stringers, for stringers.
Read more

String pattern - Roblox Wiki

A string pattern is a string composed of combinations of characters that can be used to describe all strings of a certain form. String patterns are used ...
Read more

PHP: Strings - Manual

Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Dealing with XForms ... Strings. Introduction; Installing/Configuring ...
Read more

Racquet Stringing Patterns - Klipper USA

If you are interested in having a more complete list of stringing instructions for all brands, we recommend that you consider joining the US Racquet ...
Read more

The Influence of String Pattern on Spin - Tennis Warehouse

TW University. Home; Racquets v; Strings v; Strokes v; ... Impact with closed and open patterns. ... Thin gauge strings for more grabbing and embedding.
Read more

Finding patterns in strings -

Strings in JavaScript and many other languages are smart and are built to help you. In this tutorial, you'll learn the ways you can recognize the patterns ...
Read more

Tennis Ball Spin and String Patterns Old, New, and Illegal

Spin and String Patterns Old, New, and Illegal Rod Cross, ... For the open patterns, as the strings move forward they leave a space for the ball to drop into.
Read more

PHP Strings Manipulation - Tutorialspoint

PHP Strings Manipulation - A simple and short PHP tutorial and complete reference manual for all built-in PHP functions. This tutorial is designed for ...
Read more

PHP: String Functions - Manual

Here is a truly random string generator it uses the most common string functions it ... Get the intersection of two strings using array_intersect Read more