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)

Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
Sean Cribbs
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
Vineet Kumar Saini
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
Varadharajan Mukundan
 
Php basics
Php basicsPhp basics
Php basics
hamfu
 
Subroutines
SubroutinesSubroutines
Subroutines
Krasimir Berov (Красимир Беров)
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
Krasimir Berov (Красимир Беров)
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
Chris Chubb
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
Sopan Shewale
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
leo lapworth
 
Perl
PerlPerl
Perl
RaviShankar695257
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
leo lapworth
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
tutorialsruby
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Kumar
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
Dave Cross
 
php string part 4
php string part 4php string part 4
php string part 4
monikadeshmane
 

Similar to PHP Strings and Patterns (20)

UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
Digital Insights - Digital Marketing Agency
 
Tokens in php (php: Hypertext Preprocessor).pptx
Tokens in  php (php: Hypertext Preprocessor).pptxTokens in  php (php: Hypertext Preprocessor).pptx
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
Php, mysqlpart2
Php, mysqlpart2Php, mysqlpart2
Php, mysqlpart2
Subhasis Nayak
 
php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
Sharon Manmothe
 
PHP teaching ppt for the freshers in colleeg.ppt
PHP teaching ppt for the freshers in colleeg.pptPHP teaching ppt for the freshers in colleeg.ppt
PHP teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
How to run PHP code in XAMPP.docx (1).pdf
How to run PHP code in XAMPP.docx (1).pdfHow to run PHP code in XAMPP.docx (1).pdf
How to run PHP code in XAMPP.docx (1).pdf
rajeswaria21
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
Thang Nguyen
 
PHP-01-Overview.pptfreeforeveryonecomenow
PHP-01-Overview.pptfreeforeveryonecomenowPHP-01-Overview.pptfreeforeveryonecomenow
PHP-01-Overview.pptfreeforeveryonecomenow
oliverrobertjames
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
tutorialsruby
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
tutorialsruby
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
tutorialsruby
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
sami2244
 
PHP_Lecture.pdf
PHP_Lecture.pdfPHP_Lecture.pdf
PHP_Lecture.pdf
mysthicrious
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
Regex posix
Regex posixRegex posix
Regex posix
sana mateen
 
PHP-01-Overview.ppt
PHP-01-Overview.pptPHP-01-Overview.ppt
PHP-01-Overview.ppt
NBACriteria2SICET
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Tokens in php (php: Hypertext Preprocessor).pptx
Tokens in  php (php: Hypertext Preprocessor).pptxTokens in  php (php: Hypertext Preprocessor).pptx
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
PHP teaching ppt for the freshers in colleeg.ppt
PHP teaching ppt for the freshers in colleeg.pptPHP teaching ppt for the freshers in colleeg.ppt
PHP teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
How to run PHP code in XAMPP.docx (1).pdf
How to run PHP code in XAMPP.docx (1).pdfHow to run PHP code in XAMPP.docx (1).pdf
How to run PHP code in XAMPP.docx (1).pdf
rajeswaria21
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
Thang Nguyen
 
PHP-01-Overview.pptfreeforeveryonecomenow
PHP-01-Overview.pptfreeforeveryonecomenowPHP-01-Overview.pptfreeforeveryonecomenow
PHP-01-Overview.pptfreeforeveryonecomenow
oliverrobertjames
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
sami2244
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
Ad

More from Henry Osborne (20)

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
Henry Osborne
 
Open Source Education
Open Source EducationOpen Source Education
Open Source Education
Henry Osborne
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - Linux
Henry Osborne
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with Linux
Henry Osborne
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in Linux
Henry Osborne
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
Henry Osborne
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia Support
Henry Osborne
 
Information Architecture
Information ArchitectureInformation Architecture
Information Architecture
Henry Osborne
 
Interface Design
Interface DesignInterface Design
Interface Design
Henry Osborne
 
Universal Usability
Universal UsabilityUniversal Usability
Universal Usability
Henry Osborne
 
Website Security
Website SecurityWebsite Security
Website Security
Henry Osborne
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web Services
Henry Osborne
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented Design
Henry Osborne
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
Henry Osborne
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
Henry Osborne
 
Web Programming
Web ProgrammingWeb Programming
Web Programming
Henry Osborne
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
Henry Osborne
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
Henry Osborne
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web Presence
Henry Osborne
 
Getting started with Android Programming
Getting started with Android ProgrammingGetting started with Android Programming
Getting started with Android Programming
Henry Osborne
 
Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
Henry Osborne
 
Open Source Education
Open Source EducationOpen Source Education
Open Source Education
Henry Osborne
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - Linux
Henry Osborne
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with Linux
Henry Osborne
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in Linux
Henry Osborne
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
Henry Osborne
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia Support
Henry Osborne
 
Information Architecture
Information ArchitectureInformation Architecture
Information Architecture
Henry Osborne
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web Services
Henry Osborne
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented Design
Henry Osborne
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
Henry Osborne
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
Henry Osborne
 
Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web Presence
Henry Osborne
 
Getting started with Android Programming
Getting started with Android ProgrammingGetting started with Android Programming
Getting started with Android Programming
Henry Osborne
 
Ad

Recently uploaded (20)

What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 

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