SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Strings
Strings
Char a*+=‚Baabtra‛;
Printf(‚Hello %s‛,a);
$a=‚Baabtra‛;
echo ‚Hello $a‛; //Output: Hello baabtra;
echo ‘Hello $a’; //Outputs : Hello $a
C PHP
String basics
1. Single quote strings (‘ ’)
– single quotes represent ‚simple strings,‛ where almost all characters are
used literally
2. Double quote strings(‚ ‛)
– complex strings‛ that allow for special escape sequences (for example, to
insert special characters) and for variable substitution
$a=‚Baabtra‛;
echo ‘Hello $a’;
echo ‚Hello $a n welcome‛;
Hello $a
Hello baabtra
welcome
Out put
String basics - contd
• 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
$me = ’Davey’;
$names = array (’Smith’, ’Jones’, ’Jackson’);
echo "There cannot be more than two {$me}s!";
echo "Citation: {$names[1]}[1987]";
String basics - contd
3. The Heredoc Syntax
used to declare complex strings, the functionality it provides is similar to double
quotes, with the exception that, because heredoc uses a special set of tokens to
encapsulate the string, it’s easier to declare strings that include many double-
quote characters.
$who = "World";
echo <<<TEXT
So I said, "Hello $who"
TEXT;
Escaping Literal Values
• All three string-definition syntax feature a set of several characters
that require escaping in order to be interpreted as literals.
echo ’This is ’my’ string’;
$a = 10;
echo "The value of $a is "$a".";
echo "Here’s an escaped backslash:";
String as arrays
• You can access the individual characters of a string as if they were
members of an array
$string = ’abcdef’;
echo $string[1]; // Outputs ’b’
}
String comparison == and ===
$string = ’123aa’;
if ($string == 123) {
// The string equals 123
}
• You’d expect this comparison to return false, since the two operands are not the
same. However, PHP first transparently converts the contents of $string to the
integer 123, thus making the comparison true.
• Naturally, the best way to avoid this problem is to use the identity operator ===
String functions
String functions –strcmp(), strcasecmp()
strcmp(), strcasecmp() both returns zero if the two strings passed to the
function are equal. These are identical, with the exception that the former is
case-sensitive, while the latter is not.
$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 functions –strcasencmp()
strcasencmp() allows you to only test a given number of characters
inside two strings.
$s1 = ’abcd1234’;
$s2 = ’abcd5678’;
// Compare the first four characters
echo strcasencmp ($s1, $s2, 4);
String functions –strlen()
strlen() is used to determine the length of a string
$a="baabtra mentoring parnter";
echo strlen($a);
25
Out put
String functions –strtr()
strtr() used to translate certain characters of a string into other
characters
• Single character version
echo strstr (’abc’, ’a’, ’1’);
• Multiple-character version
$subst = array (’1’ => ’one’,’2’ => ’two’);
echo strtr (’123’, $subst);
1bc
Out put
onetwo3
Out put
String functions –strpos()
• strpos() allows you to find the position of a substring inside a string. It
returns either the numeric position of the substring’s first occurrence within
the string, or false if a match could not be found.
• 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.
$haystack = ’123456123456’;
$needle = ’123’;
echo strpos ($haystack, $needle);
echo strpos ($haystack, $needle, 1);
0
Out put
6
String functions –stripos() , strrpos()
• stripos() is case-insensitive version of strpos()
echo stripos(’Hello World’, ’hello’);
• Strpos() does the same as strpos(), but in the revers order
echo strrpos (’123123’, ’123’);
0
Out put
3
Out put
String functions –strstr()
• The strstr() function works similarly to strpos() in that it searches the main
string for a substring. The only real difference is that this function returns the
portion of the main string that starts with the sub string instead of the latter’s
position:
$haystack = ’123456’;
$needle = ’34’;
echo strstr ($haystack, $needle);
3456
Out put
String functions –stristr()
• stristr() is case-insensitive version of strstr()
echo stristr(’Hello My World’, ’my’); My World
Out put
String functions –str_replace(), str_ireplace()
• str_replace() used to replace portions of a string with a different substring
echo str_replace("World", "Reader", "Hello World");
• Str_ireplace() is the case insensitive version of str_replace()
echo str_ireplace("world", "Reader", "Hello World");
• Optionally, you can specify a third parameter, that the function fills, upon
return, with the number of substitutions made:
$a = 0;
str_replace (’a’, ’b’, ’a1a1a1’, $a);
echo $a;
Hello Reader
Out put
Hello Reader
Out put
3
String functions –str_replace(), str_ireplace()
• 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 arrays
• echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "HelloWorld");
• echo str_replace(array("Hello", "World"), "Bye", "Hello World");
Bye Bye
Hello Reader
String functions –substr()
• The very flexible and powerful substr() function allows you to extract
a substring from a larger string.
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
String functions –number_format()
• Number formatting is typically used when you wish to output a
number and separate its digits into thousands and decimal points
• echo number_format("100000.698‚ , 3 , "," , ‚ ");
100 000,698
Number to be formatted
Number of decimal places to be rouned
decimal separator
Thousand separator
Output
Regular expressions
Regular Expressions
• Perl Compatible Regular Expressions (normally abbreviated as
‚PCRE‛) offer a very powerful string-matching and replacement
mechanism that far surpasses anything we have examined so far.
• The real power of regular expressions comes into play when you
don’t know the exact string that you want to match
Regular Expressions - Delimiters
• A regular expression is always delimited by a starting and ending
character.
• Any character can be used for this purpose (as long as the
beginning and ending delimiter match); since any occurrence of
this character inside the expression itself must be escaped, it’s
usually a good idea to pick a delimiter that isn’t likely to appear
inside the expression.
Regular Expressions – Meta characters
• However, every metacharacter represents a single character in the
matched expression.
. (dot)Match any character
ˆ Match the start of the string
$ Match the end of the string
s Match any whitespace character
d Match any digit
w Match any ‚word‛ character
Regular Expressions – Meta characters
• Meta characters can also be expressed using grouping expressions. For example, a
series of valid alternatives for a character can be provided by using square brackets:
/ab[cd]e/
• You can also use other metacharacters, and provide ranges of valid characters inside a
grouping expression:
/ab[c-ed]/
The expression will match abce or abde
This will match abc, abd, abe and any combination
of ab followed by a digit.
Regular Expressions – Quanitifiers
• This will match abc, abd, abe and any combination of ab followed by a digit.
* The character can appear zero or more times
+ The character can appear one or more times
? The character can appear zero or one times
{n,m} The character can appear at least n times, and no more than m.
Either parameter can be omitted to indicated a minimum limit
with nomaximum, or a maximum limit without aminimum,
but not both.
ab?c matches both ac and abc,
ab{1,3}c matches abc, abbc and abbbc.
Example
Regular Expressions – Sub-Expressions
• A sub-expression is a regular expression contained within the
main regular expression (or another sub-expression); you define
one by encapsulating it in parentheses:
/a(bc.)e/
/a(bc.)+e/
Example
Matching and Extracting Strings
• The preg_match() function can be used to match a regular
expression against a given string.
$name = "Davey Shafik";
// Simple match
$regex = "/[a-zA-Zs]/";
if (preg_match($regex, $name)) {
// Valid Name
}
Example
Questions?
‚A good question deserve a good grade…‛
Self Check !!
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

Contenu connexe

Tendances

Php basics
Php basicsPhp basics
Php basics
hamfu
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 

Tendances (17)

Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Php basics
Php basicsPhp basics
Php basics
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
Subroutines
SubroutinesSubroutines
Subroutines
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
php string part 4
php string part 4php string part 4
php string part 4
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Wx::Perl::Smart
Wx::Perl::SmartWx::Perl::Smart
Wx::Perl::Smart
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
 
1 the ruby way
1   the ruby way1   the ruby way
1 the ruby way
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Perl
PerlPerl
Perl
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 

En vedette

How to report a bug
How to report a bugHow to report a bug
How to report a bug
Sandy Smith
 
EDUPUB 2013: Schema.org LRMI and A11Y for Discovery
EDUPUB 2013: Schema.org LRMI and A11Y for DiscoveryEDUPUB 2013: Schema.org LRMI and A11Y for Discovery
EDUPUB 2013: Schema.org LRMI and A11Y for Discovery
Gerardo Capiel
 

En vedette (20)

Lessons from a Dying CMS
Lessons from a Dying CMSLessons from a Dying CMS
Lessons from a Dying CMS
 
Grokking regex
Grokking regexGrokking regex
Grokking regex
 
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
 
Dom
DomDom
Dom
 
Multibyte string handling in PHP
Multibyte string handling in PHPMultibyte string handling in PHP
Multibyte string handling in PHP
 
TDA Center Depok update 2014 (Concept)
TDA Center Depok update 2014 (Concept)TDA Center Depok update 2014 (Concept)
TDA Center Depok update 2014 (Concept)
 
Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"Hyperlocalisation or "localising everything"
Hyperlocalisation or "localising everything"
 
Unicode Regular Expressions
Unicode Regular ExpressionsUnicode Regular Expressions
Unicode Regular Expressions
 
Architecting with Queues for Scale, Speed, and Separation (DCPHP 3/11/15)
Architecting with Queues for Scale, Speed, and Separation (DCPHP 3/11/15)Architecting with Queues for Scale, Speed, and Separation (DCPHP 3/11/15)
Architecting with Queues for Scale, Speed, and Separation (DCPHP 3/11/15)
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
 
GAIQ - Regular expressions-google-analytics
GAIQ - Regular expressions-google-analyticsGAIQ - Regular expressions-google-analytics
GAIQ - Regular expressions-google-analytics
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Don't Fear the Regex LSP15
Don't Fear the Regex LSP15Don't Fear the Regex LSP15
Don't Fear the Regex LSP15
 
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
 
How to report a bug
How to report a bugHow to report a bug
How to report a bug
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Architecting with Queues - Northeast PHP 2015
Architecting with Queues - Northeast PHP 2015Architecting with Queues - Northeast PHP 2015
Architecting with Queues - Northeast PHP 2015
 
EDUPUB 2013: Schema.org LRMI and A11Y for Discovery
EDUPUB 2013: Schema.org LRMI and A11Y for DiscoveryEDUPUB 2013: Schema.org LRMI and A11Y for Discovery
EDUPUB 2013: Schema.org LRMI and A11Y for Discovery
 

Similaire à Intoduction to php strings

Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
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
 

Similaire à Intoduction to php strings (20)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Strings
StringsStrings
Strings
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Regular expressions in oracle
Regular expressions in oracleRegular expressions in oracle
Regular expressions in oracle
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
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
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
 
lecture5.ppt
lecture5.pptlecture5.ppt
lecture5.ppt
 
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdfFUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
FUNDAMENTALS OF REGULAR EXPRESSION (RegEX).pdf
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Strings
StringsStrings
Strings
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 

Plus de baabtra.com - No. 1 supplier of quality freshers

Plus de baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Intoduction to php strings

  • 2. Strings Char a*+=‚Baabtra‛; Printf(‚Hello %s‛,a); $a=‚Baabtra‛; echo ‚Hello $a‛; //Output: Hello baabtra; echo ‘Hello $a’; //Outputs : Hello $a C PHP
  • 3. String basics 1. Single quote strings (‘ ’) – single quotes represent ‚simple strings,‛ where almost all characters are used literally 2. Double quote strings(‚ ‛) – complex strings‛ that allow for special escape sequences (for example, to insert special characters) and for variable substitution $a=‚Baabtra‛; echo ‘Hello $a’; echo ‚Hello $a n welcome‛; Hello $a Hello baabtra welcome Out put
  • 4. String basics - contd • 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 $me = ’Davey’; $names = array (’Smith’, ’Jones’, ’Jackson’); echo "There cannot be more than two {$me}s!"; echo "Citation: {$names[1]}[1987]";
  • 5. String basics - contd 3. The Heredoc Syntax used to declare complex strings, the functionality it provides is similar to double quotes, with the exception that, because heredoc uses a special set of tokens to encapsulate the string, it’s easier to declare strings that include many double- quote characters. $who = "World"; echo <<<TEXT So I said, "Hello $who" TEXT;
  • 6. Escaping Literal Values • All three string-definition syntax feature a set of several characters that require escaping in order to be interpreted as literals. echo ’This is ’my’ string’; $a = 10; echo "The value of $a is "$a"."; echo "Here’s an escaped backslash:";
  • 7. String as arrays • You can access the individual characters of a string as if they were members of an array $string = ’abcdef’; echo $string[1]; // Outputs ’b’ }
  • 8. String comparison == and === $string = ’123aa’; if ($string == 123) { // The string equals 123 } • You’d expect this comparison to return false, since the two operands are not the same. However, PHP first transparently converts the contents of $string to the integer 123, thus making the comparison true. • Naturally, the best way to avoid this problem is to use the identity operator ===
  • 10. String functions –strcmp(), strcasecmp() strcmp(), strcasecmp() both returns zero if the two strings passed to the function are equal. These are identical, with the exception that the former is case-sensitive, while the latter is not. $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 }
  • 11. String functions –strcasencmp() strcasencmp() allows you to only test a given number of characters inside two strings. $s1 = ’abcd1234’; $s2 = ’abcd5678’; // Compare the first four characters echo strcasencmp ($s1, $s2, 4);
  • 12. String functions –strlen() strlen() is used to determine the length of a string $a="baabtra mentoring parnter"; echo strlen($a); 25 Out put
  • 13. String functions –strtr() strtr() used to translate certain characters of a string into other characters • Single character version echo strstr (’abc’, ’a’, ’1’); • Multiple-character version $subst = array (’1’ => ’one’,’2’ => ’two’); echo strtr (’123’, $subst); 1bc Out put onetwo3 Out put
  • 14. String functions –strpos() • strpos() allows you to find the position of a substring inside a string. It returns either the numeric position of the substring’s first occurrence within the string, or false if a match could not be found. • 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. $haystack = ’123456123456’; $needle = ’123’; echo strpos ($haystack, $needle); echo strpos ($haystack, $needle, 1); 0 Out put 6
  • 15. String functions –stripos() , strrpos() • stripos() is case-insensitive version of strpos() echo stripos(’Hello World’, ’hello’); • Strpos() does the same as strpos(), but in the revers order echo strrpos (’123123’, ’123’); 0 Out put 3 Out put
  • 16. String functions –strstr() • The strstr() function works similarly to strpos() in that it searches the main string for a substring. The only real difference is that this function returns the portion of the main string that starts with the sub string instead of the latter’s position: $haystack = ’123456’; $needle = ’34’; echo strstr ($haystack, $needle); 3456 Out put
  • 17. String functions –stristr() • stristr() is case-insensitive version of strstr() echo stristr(’Hello My World’, ’my’); My World Out put
  • 18. String functions –str_replace(), str_ireplace() • str_replace() used to replace portions of a string with a different substring echo str_replace("World", "Reader", "Hello World"); • Str_ireplace() is the case insensitive version of str_replace() echo str_ireplace("world", "Reader", "Hello World"); • Optionally, you can specify a third parameter, that the function fills, upon return, with the number of substitutions made: $a = 0; str_replace (’a’, ’b’, ’a1a1a1’, $a); echo $a; Hello Reader Out put Hello Reader Out put 3
  • 19. String functions –str_replace(), str_ireplace() • 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 arrays • echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "HelloWorld"); • echo str_replace(array("Hello", "World"), "Bye", "Hello World"); Bye Bye Hello Reader
  • 20. String functions –substr() • The very flexible and powerful substr() function allows you to extract a substring from a larger string. 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
  • 21. String functions –number_format() • Number formatting is typically used when you wish to output a number and separate its digits into thousands and decimal points • echo number_format("100000.698‚ , 3 , "," , ‚ "); 100 000,698 Number to be formatted Number of decimal places to be rouned decimal separator Thousand separator Output
  • 23. Regular Expressions • Perl Compatible Regular Expressions (normally abbreviated as ‚PCRE‛) offer a very powerful string-matching and replacement mechanism that far surpasses anything we have examined so far. • The real power of regular expressions comes into play when you don’t know the exact string that you want to match
  • 24. Regular Expressions - Delimiters • A regular expression is always delimited by a starting and ending character. • Any character can be used for this purpose (as long as the beginning and ending delimiter match); since any occurrence of this character inside the expression itself must be escaped, it’s usually a good idea to pick a delimiter that isn’t likely to appear inside the expression.
  • 25. Regular Expressions – Meta characters • However, every metacharacter represents a single character in the matched expression. . (dot)Match any character ˆ Match the start of the string $ Match the end of the string s Match any whitespace character d Match any digit w Match any ‚word‛ character
  • 26. Regular Expressions – Meta characters • Meta characters can also be expressed using grouping expressions. For example, a series of valid alternatives for a character can be provided by using square brackets: /ab[cd]e/ • You can also use other metacharacters, and provide ranges of valid characters inside a grouping expression: /ab[c-ed]/ The expression will match abce or abde This will match abc, abd, abe and any combination of ab followed by a digit.
  • 27. Regular Expressions – Quanitifiers • This will match abc, abd, abe and any combination of ab followed by a digit. * The character can appear zero or more times + The character can appear one or more times ? The character can appear zero or one times {n,m} The character can appear at least n times, and no more than m. Either parameter can be omitted to indicated a minimum limit with nomaximum, or a maximum limit without aminimum, but not both. ab?c matches both ac and abc, ab{1,3}c matches abc, abbc and abbbc. Example
  • 28. Regular Expressions – Sub-Expressions • A sub-expression is a regular expression contained within the main regular expression (or another sub-expression); you define one by encapsulating it in parentheses: /a(bc.)e/ /a(bc.)+e/ Example
  • 29. Matching and Extracting Strings • The preg_match() function can be used to match a regular expression against a given string. $name = "Davey Shafik"; // Simple match $regex = "/[a-zA-Zs]/"; if (preg_match($regex, $name)) { // Valid Name } Example
  • 30. Questions? ‚A good question deserve a good grade…‛
  • 32. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 33. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com