SlideShare a Scribd company logo
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 = “henry@thinktankesolutions.com";
$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

More Related Content

What's hot (15)

KEY
Achieving Parsing Sanity In Erlang
Sean Cribbs
 
PDF
Sorting arrays in PHP
Vineet Kumar Saini
 
PDF
Perl Scripting
Varadharajan Mukundan
 
PPT
Php basics
hamfu
 
PPT
Php Chapter 4 Training
Chris Chubb
 
PPT
Perl Presentation
Sopan Shewale
 
PDF
DBIx::Class introduction - 2010
leo lapworth
 
PDF
DBIx::Class beginners
leo lapworth
 
PDF
perl_lessons
tutorialsruby
 
PDF
PHP Unit 4 arrays
Kumar
 
PDF
Improving Dev Assistant
Dave Cross
 
PPTX
php string part 4
monikadeshmane
 
Achieving Parsing Sanity In Erlang
Sean Cribbs
 
Sorting arrays in PHP
Vineet Kumar Saini
 
Perl Scripting
Varadharajan Mukundan
 
Php basics
hamfu
 
Php Chapter 4 Training
Chris Chubb
 
Perl Presentation
Sopan Shewale
 
DBIx::Class introduction - 2010
leo lapworth
 
DBIx::Class beginners
leo lapworth
 
perl_lessons
tutorialsruby
 
PHP Unit 4 arrays
Kumar
 
Improving Dev Assistant
Dave Cross
 
php string part 4
monikadeshmane
 

Similar to PHP Strings and Patterns (20)

PDF
Barcelona.pm Curs1211 sess01
Javier Arturo Rodríguez
 
PDF
php_string.pdf
Sharon Manmothe
 
PDF
tutorial7
tutorialsruby
 
PDF
tutorial7
tutorialsruby
 
PDF
Learning Perl 6
brian d foy
 
PPT
Strings
Mitali Chugh
 
PPT
Introduction to Perl
Sway Wang
 
PPTX
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
AbhimanyuChaure
 
PDF
Strings in Python
nitamhaske
 
PDF
Lecture 23
rhshriva
 
PPTX
Php functions
JIGAR MAKHIJA
 
PDF
Learning Perl 6 (NPW 2007)
brian d foy
 
PDF
perl_lessons
tutorialsruby
 
PPTX
First steps in C-Shell
Brahma Killampalli
 
PPTX
Day5 String python language for btech.pptx
mrsam3062
 
PPT
Introduction to regular expressions
Ben Brumfield
 
PDF
c programming
Arun Umrao
 
PDF
How to write code you won't hate tomorrow
Pete McFarlane
 
PPTX
Presentation on php string function part-2
Mysoftheaven (BD) Ltd.
 
PDF
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
Barcelona.pm Curs1211 sess01
Javier Arturo Rodríguez
 
php_string.pdf
Sharon Manmothe
 
tutorial7
tutorialsruby
 
tutorial7
tutorialsruby
 
Learning Perl 6
brian d foy
 
Strings
Mitali Chugh
 
Introduction to Perl
Sway Wang
 
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
AbhimanyuChaure
 
Strings in Python
nitamhaske
 
Lecture 23
rhshriva
 
Php functions
JIGAR MAKHIJA
 
Learning Perl 6 (NPW 2007)
brian d foy
 
perl_lessons
tutorialsruby
 
First steps in C-Shell
Brahma Killampalli
 
Day5 String python language for btech.pptx
mrsam3062
 
Introduction to regular expressions
Ben Brumfield
 
c programming
Arun Umrao
 
How to write code you won't hate tomorrow
Pete McFarlane
 
Presentation on php string function part-2
Mysoftheaven (BD) Ltd.
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
Ad

More from Henry Osborne (20)

PPTX
Android Fundamentals
Henry Osborne
 
PPTX
Open Source Education
Henry Osborne
 
PPTX
Security Concepts - Linux
Henry Osborne
 
PPTX
Networking Basics with Linux
Henry Osborne
 
PPTX
Disk and File System Management in Linux
Henry Osborne
 
PPTX
Drawing with the HTML5 Canvas
Henry Osborne
 
PPTX
HTML5 Multimedia Support
Henry Osborne
 
PPTX
Information Architecture
Henry Osborne
 
PPTX
Interface Design
Henry Osborne
 
PPTX
Universal Usability
Henry Osborne
 
PPTX
Website Security
Henry Osborne
 
PPTX
XML and Web Services
Henry Osborne
 
PPTX
Elements of Object-oriented Design
Henry Osborne
 
PPTX
Database Programming
Henry Osborne
 
PPTX
OOP in PHP
Henry Osborne
 
PPTX
Web Programming
Henry Osborne
 
PPTX
PHP Basics
Henry Osborne
 
PPTX
Activities, Fragments, and Events
Henry Osborne
 
PPTX
Establishing a Web Presence
Henry Osborne
 
PPTX
Getting started with Android Programming
Henry Osborne
 
Android Fundamentals
Henry Osborne
 
Open Source Education
Henry Osborne
 
Security Concepts - Linux
Henry Osborne
 
Networking Basics with Linux
Henry Osborne
 
Disk and File System Management in Linux
Henry Osborne
 
Drawing with the HTML5 Canvas
Henry Osborne
 
HTML5 Multimedia Support
Henry Osborne
 
Information Architecture
Henry Osborne
 
Interface Design
Henry Osborne
 
Universal Usability
Henry Osborne
 
Website Security
Henry Osborne
 
XML and Web Services
Henry Osborne
 
Elements of Object-oriented Design
Henry Osborne
 
Database Programming
Henry Osborne
 
OOP in PHP
Henry Osborne
 
Web Programming
Henry Osborne
 
PHP Basics
Henry Osborne
 
Activities, Fragments, and Events
Henry Osborne
 
Establishing a Web Presence
Henry Osborne
 
Getting started with Android Programming
Henry Osborne
 
Ad

Recently uploaded (20)

PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 

PHP Strings and Patterns

  • 3. String Basics hex and octal notation to display an asterisk: echo "x2a"; echo "052";
  • 4. Variable Interpolation $who = "World"; echo "Hello $whon"; // Shows "Hello World" followed by a newline echo ’Hello $whon’; // Shows "Hello $whon"
  • 5. 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]";
  • 6. 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;
  • 7. 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
  • 8. 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
  • 9. 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.
  • 11. String Comparison, cont’d $string = ’123aa’; if ($string == 123) { // The string equals 123 }
  • 12. 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 }
  • 13. String Comparison, cont’d $s1 = ’abcd1234’; $s2 = ’abcd5678’; // Compare the first four characters echo strncasecmp ($s1, $s2, 4);
  • 14. String Search $haystack = "abcdefg"; $needle = ’abc’; if (strpos ($haystack, $needle) !== false) { echo ’Found’; }
  • 15. String Search, cont’d $haystack = ’123456123456’; $needle = ’123’; echo strpos ($haystack, $needle); // outputs 0 echo strpos ($haystack, $needle, 1); // outputs 6
  • 16. String Search, cont’d $haystack = ’123456’; $needle = ’34’; echo strstr ($haystack, $needle); // outputs 3456
  • 17. 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.
  • 18. 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
  • 19. Matching Against a Mask $string = ’133445abcdef’; $mask = ’12345’; echo strspn ($string, $mask); // Outputs 6
  • 20. 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.
  • 21. Matching Against a Mask, cont’d $string = ’1abc234’; $mask = ’abc’; echo strspn ($string, $mask, 1, 4);
  • 22. Search and Replace Operations echo str_replace("World", "Reader", "Hello World"); echo str_ireplace("world", "Reader", "Hello World");
  • 23. 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");
  • 24. Search and Replace, cont’d echo substr_replace("Hello World", "Reader", 6); echo substr_replace("Canned tomatoes are good", "potatoes", 7, 8);
  • 25. Search and Replace, cont’d $user = “[email protected]"; $name = substr_replace($user, "", strpos($user, ’@’); echo "Hello " . $name;
  • 26. 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
  • 28. Formatting Numbers // Shows 100,001 echo number_format("100000.698"); // Shows 100 000,698 echo number_format("100000.698", 3, ",", " ");
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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__);
  • 33. Parsing Formatted Input $data = ’123 456 789’; $format = ’%d %d %d’; var_dump (sscanf ($data, $format));

Editor's Notes

  • #2: Strings can be used to store binary data of any kind—as well as text encoded in a way that PHP does not understand natively, but that one of its extensions can manipulate directly.String manipulation is a very important skill for every PHP developer
  • #4: Strings can be defined using one of several methodsSingle quotes: “simple strings,” where almost all characters are used literallyDouble quotes: encapsulate “complex strings” that allow for special escape sequencesand for variable substitution, which makes it possible to embed the value of a variable directly in a string, without the need for any special operator.Escape sequences are sometimes called control characters and take the form of a backslash (\) followed by one or more characters
  • #5: Variables can be embedded directly inside a double-quote string by simply typing their name.
  • #6: Clearly , this “simple” syntax won’t work in those situations in which the name of the variable you want to interpolated is positioned in such a way inside the string that the parser wouldn’t be able to parse its name in the way you intend it to. In these cases, you can encapsulate the variable’s name in braces
  • #7: A heredoc string is delimited by the special operator &lt;&lt;&lt; followed by an identifier. You must then close the string using the same identifier, optionally followed by a semicolon, placed at the very beginning of its own line (that is, it should not be pre-ceded by whitespace). Heredoc identifiers must follow the same rules are variable naming (explained in the PHP Basics chapter), and are similarly case-sensitive.
  • #11: Comparison is, perhaps, one of the most common operations performed on strings. At times, PHP’s type-juggling mechanisms also make it the most maddening—particularly because strings that can be interpreted as numbers are often transparently converted to their numeric equivalent.
  • #12: PHP first transparently converts the contents of $string to the integer 123, thus making the comparison true.Best way to avoid this problem is to use the identity operator === whenever you are performing a comparison that could potentially lead to type-juggling problems
  • #13: In addition to comparison operators, you can also use the specialized functions strcmp() and strcasecmp() to match strings.These are identical, with the exception that the former is case-sensitive, while the latter is not. In both cases, a result of zero indicates that the two strings passed to the function are equal
  • #14: A further variant of strcasecmp(), strncasecmp() allows you to only test a given number of characters inside two strings.
  • #15: The simplest way to search inside a string is to use the strpos() and strstr() families of functions. The former allows you to find the position of a substring (usually called the needle) inside a string (called the haystack). It returns either the numeric position of the needle’s first occurrence within the haystack, or false if a match could not be found.
  • #16: You can also specify an optional third parameter to strpos() to indicate that you want the search to start from a specific position within the haystack
  • #17: The strstr() function works similarly to strpos() in that it searches the haystack for a needle. The only real difference is that this function returns the portion of the haystack that starts with the needle instead of the latter’s position
  • #19: Both strpos() and strstr() are case sensitive and start looking for the needle from the beginning of the haystack. However, PHP provides variants that work in a case-insensitive way or start looking for the needle from the end of the haystack
  • #20: You can use the strspn() function to match a string against a “whitelist” mask of allowed characters. This function returns the length of the initial segment of the string that contains any of the characters specified in the mask
  • #22: Both strspn() and strcspn() accept two optional parameters that define the starting position and the length of the string to examineIn the example above, strspn() will start examining the string from the second character (index 1), and continue for up to four characters—however, only the first three character it encounters satisfy the mask’s constraints and, therefore, the script outputs 3
  • #23: Simple substitutions are performed using str_replace() (as wellas its case-insensitive variation, str_ireplace()) and substr_replace()
  • #24: If you need to search and replace more than one needle at a time, you can pass the first two arguments to str_replace() in the form of arraysFirst example: the replacements are made based on array indexes—the first element of the search array is replaced by the first element of the replacement array, and the output is “Bonjour Monde”Second example: only the needle argument is an array; in this case, both search terms are replaced by the same string resulting in “Bye Bye”
  • #25: If you need to replace a portion of a needle of which you already know the starting and ending point, you can use substr_replace()
  • #26: Combining substr_replace() with strpos() can prove to be a powerful toolBy using strpos() to locate the first occurrence of the @ symbol, we can replace the rest of the e-mail address with an empty string, leaving us with just the username, which we output in greeting
  • #27: substr() function allows you to extract a substring from a larger stringIt takes three parameters: the string to be worked on, a starting index and an optional lengthThe starting index can be specified as either a positive integer (meaning the index of a character in the string starting from the beginning) or a negative integer (meaning the index of a character starting from the end).
  • #28: PHP provides a number of different functions that can be used to format output in a variety of ways. Some of them are designed to handle special data types—for example, numbers of currency values—while others provide a more generic interface for formatting strings according to more complex rules.Formatting rules are sometimes governed by locale considerations.
  • #29: The number_format() function accepts 1, 2 or 4 arguments (but not three)If only one argument is given, the default formatting is used: the number will be rounded to the nearest integer, and a comma will be used to separate thousandsIf two arguments are given, the number will be rounded to the given number of decimal places and a period and comma will be used to separate decimals and thousands, respectively.Should you pass in all four parameters, the number will be rounded to the number of decimal places given, and number_format() will use the first character of the third and fourth arguments as decimal and thousand separators respectively
  • #35: Strings can be used to store binary data of any kind—as well as text encoded in a way that PHP does not understand natively, but that one of its extensions can manipulate directly.String manipulation is a very important skill for every PHP developer