SlideShare une entreprise Scribd logo
1  sur  36
PHP Strings
Outline
What are Strings ?
• A string is a series of characters.
• Can contain any arbitrary number of characters, the only
limit is the memory limit.
Ways To Write a String
Escaping characters
• Escaping is done using the backslash “” character :
$x = “He said “I’m a developer” ”;
$e = ‘He said ”I’m a developer” ’;
$d = “ $z ”; // $d has the value of the variable $z
$r = “ $z ”; // r has the value: $z
Special characters
• The most frequently used special characters we have are :
o n : linefeed
o t : the tab ( a number of spaces )
• We can only output these characters in double quoted
and heredoc strings.
• echo “Hin PHP”; // prints “Hi” then “PHP” in the next line
• echo ‘Hi n PHP’; // prints “Hi n PHP”
Curly syntax
• In double quoted and heredoc strings, you can have the
following :
$x[10] = “great”;
$x[‘name’] = “strings”;
$y = “ This is {$x[10]} ”; // This is great
$z = “ {$x[‘name’]} are flexible.”; // strings are flexible.
Accessing characters
• Strings can be accessed like arrays to get a specific
character :
$x = “String”;
echo $x[0]; // S
echo $x[1]; // t
echo $x[2]; // r
String Operations
• Concatenation operator “.”:
$x = “Hello ” . “ world”; // Hello world
• Concatenating assignment operator :
$x = “Hello ”;
$x .= “world” // Hello world
String Comparison
1. Can compare strings using “==“ operator :
if( $x == “Hi” )
echo “yes”;
1. Can use strcmp() built-in function :
if( strcmp( $x, “Hi”) == 0 )
echo “yes”;
1. Use strcasecmp() for case insensitive comparisons :
if( strcasecmp( “hi”, “Hi”) == 0 )
echo “yes”;
String Length
The function strlen() returns the length of the string:
Example:
echo strlen( “A string” ); // 8
Searching Strings
int strpos ( string $haystack , mixed $needle [, int $offset = 0
] )
Returns the numeric position of the first occurrence of needle
in the haystack string.
Example:
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme); // 0
Replacing Strings
mixed str_replace ( mixed $search , mixed $replace , mixed
$subject [, int &$count ] )
This function returns a string or an array with all occurrences
of search in subject replaced with the given replace value.
Example:
echo str_replace( “Hi”, “Hello”, “Hi strings.” ); // Hello
strings.
Extracting Strings
string substr ( string $string , int $start [, int $length ] )
Returns the portion of string specified by the start and length
parameters.
Example :
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
Splitting Strings
array explode ( string $delimiter , string $string [, int $limit ])
Returns an array of strings, each of which is a substring of
string formed by splitting it on boundaries formed by the
string delimiter.
Example :
$string = “this is a string";
$pieces = explode(" ", $string);
var_dump($pieces); // prints an array containing the parts
Joining Strings
string implode ( string $glue , array $pieces )
Join array elements with a glue string.
Example :
$array = array( “this”, “is”, “a”, “string” );
$string= implode(" ", $array);
echo $string; // this is a string
Exercise
Write a PHP function that reverses the string words, so If we
have a string like this :
this is the php strings lesson
The function should return this :
lesson strings php the is this
Exercise solution
<?php
function reverse_words($string){
$result = "";
$exploded = explode(" ", $string);
$reversed = array_reverse($exploded);
$result = implode(" ", $reversed);
return $result;
}
reverse_words( "this is the php strings lesson" );
?>
Formatting Strings
string number_format ( float $number , int $decimals = 0 ,
string $dec_point = '.' , string $thousands_sep = ',' )
This function formats a number according to the passed
arguments.
Example :
$number = 1234.5678;
$english_format_number = number_format($number,
2, '.', ''); // 1234.57
Formatting Strings
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
Returns a string produced according to the formatting string
format.
Example
printf(“My name is %s and my age is %d", “John”, 20 ); //
My name is John and my age is 20
For a complete list of details, visit :
http://php.net/manual/en/function.sprintf.php
Regular Expressions
• Regular expressions ( Regex ) provide flexible means for
matching strings of text.
• For example :
How can I check whether the user supplied a valid e-
mail or not ?
• There should be something that tells :
Is the string like some characters/digits then @ then
some characters/digits then .com ??? Here comes the
regex.
Meta Characters
Meta characters are characters the have some special meanings
in the regex pattern.
Character Description
 general escape character with several uses
^ assert start of subject (or line, in multiline mode)
$ assert end of subject (or line, in multiline mode)
. match any character except newline (by default)
[ start character class definition
] End character class definition
| start of alternative branch
( Start of sub pattern
) End of sub pattern
Meta Characters
Character Description
? 0 or 1
* 0 or more
+ 1 or more
{ Start min/max number of occurrences
} End min/max number of occurrences
^ negate the class, but only if it is the first character
- Character range
Character Classes
Character classes define the type of characters in the regex pattern.
Class Description
d Matches any numeric character - same as [0-9]
D Matches any non-numeric character - same as [^0-9]
s Matches any whitespace character - same as [ tnrfv]
S Matches any non-whitespace character - same as [^ tnrfv]
w Matches any alphanumeric character - same as [a-zA-Z0-9_]
W Matches any non-alphanumeric character - same as [^a-zA-Z0-9_]
Regex Examples
Regular
expression
(pattern)
Match (Subject ) Not match Comment
world Hello world Hello Jim
Match if the pattern is
present anywhere in the
subject
^world world class Hello world
Match if the pattern is
present at the beginning
of the subject
world$ Hello world world class
Match if the pattern is
present at the end of the
subject
/world/i This WoRLd Hello Jim
Makes a search in case
insensitive mode
^world$ world Hello world
The string contains only
the "world"
world*
worl, world,
worlddd
wor
There is 0 or more "d"
after "worl"
world+ world, worlddd worl
There is at least 1 "d"
after "worl"
Regex Examples
Regular
expression
(pattern)
Match (Subject ) Not match Comment
world? worl, world, worly wor, wory
There is 0 or 1 "d" after
"worl"
world{1} world worly
There is 1 "d" after
"worl"
world{1,} world, worlddd worly
There is 1 ore more "d"
after "worl"
world{2,3} worldd, worlddd world
There are 2 or 3 "d" after
"worl"
wo(rld)* wo, world, worldold wa
There is 0 or more "rld"
after "wo"
earth|world earth, world sun
The string contains the
"earth" or the "world"
Regex Examples
Regular
expression
(pattern)
Match (Subject ) Not match Comment
w.rld world, wwrld wrld
Any character in place of
the dot.
^.{5}$ world, earth sun
A string with exactly 5
characters
[abc] abc, bbaccc sun
There is an "a" or "b" or
"c" in the string
[a-z] world WORLD
There are any lowercase
letter in the string
[a-zA-Z]
world, WORLD,
Worl12
123
There are any lower- or
uppercase letter in the
string
[^wW] earth w, W
The actual character can
not be a "w" or "W"
Regex Functions
int preg_match ( string $pattern , string $subject [, array
&$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Searches subject for a match to the regular expression given
in pattern. It will stop by the first occurrence of the pattern.
Example:
$x = preg_match( “/php*/”, “phpppp”, $result ); // returns 1
var_dump($result); // array(1) { [0]=> string(6) "phpppp" }
Regex Functions
int preg_match_all ( string $pattern , string $subject , array
&$matches [, int $flags = PREG_PATTERN_ORDER [, int
$offset = 0 ]] )
Searches subject for a match to the regular expression given
in pattern. It gets all the occurrences of the pattern in the
string.
Example:
$x = preg_match_all( “/php/”, “phpp phpzz”, $result ); // returns 1
var_dump($result); // array(1) { [0]=> array(2) { [0]=> string(3)
"php" [1]=> string(3) "php" } }
Regex Functions
mixed preg_replace ( mixed $pattern , mixed
$replacement , mixed $subject [, int $limit = -1 [, int
&$count ]] )
Searches subject for matches to pattern and replaces them
with replacement.
Example:
$x = preg_replace( “/php*/”, “hi” ,“phpp phppz”);
echo $x ; // hi hiz
Exercise
Write a PHP snippet that checks whether the user has
entered a valid email or not ( the email should end with a
.com ).
Exercise Solution
<?php
$email = "myemail1@example.com";
if(preg_match("/[w]+@[w]+.com/", $email) == 1 )
echo "Valid email";
else
echo "Invalid email";
?>
More info about Regex
For more info about regular expressions, please visit :
http://www.php.net/manual/en/reference.pcre.pattern.syntax.p
Assignment
1- Write a function that calculates the number of the words a string has.
2- Write a PHP script that matches the following phone numbers :
718 498 1043
718 198-1043
What's Next?
• Web Programming.
Questions?

Contenu connexe

Tendances

Tendances (20)

JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Php forms
Php formsPhp forms
Php forms
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
XML Schema
XML SchemaXML Schema
XML Schema
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 

En vedette

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionAhmed Swilam
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
Associative arrays in PHP
Associative arrays in PHPAssociative arrays in PHP
Associative arrays in PHPSuraj Motee
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersMohammed Mushtaq Ahmed
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2Yang Bruce
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel frameworkBo-Yi Wu
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web frameworkBo-Yi Wu
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP SecurityZendCon
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 

En vedette (20)

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Associative arrays in PHP
Associative arrays in PHPAssociative arrays in PHP
Associative arrays in PHP
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel framework
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web framework
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 

Similaire à Class 5 - PHP Strings

Similaire à Class 5 - PHP Strings (20)

php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
PHP - Introduction to String Handling
PHP -  Introduction to  String Handling PHP -  Introduction to  String Handling
PHP - Introduction to String Handling
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 

Dernier

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Dernier (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Class 5 - PHP Strings

  • 3. What are Strings ? • A string is a series of characters. • Can contain any arbitrary number of characters, the only limit is the memory limit.
  • 4. Ways To Write a String
  • 5. Escaping characters • Escaping is done using the backslash “” character : $x = “He said “I’m a developer” ”; $e = ‘He said ”I’m a developer” ’; $d = “ $z ”; // $d has the value of the variable $z $r = “ $z ”; // r has the value: $z
  • 6. Special characters • The most frequently used special characters we have are : o n : linefeed o t : the tab ( a number of spaces ) • We can only output these characters in double quoted and heredoc strings. • echo “Hin PHP”; // prints “Hi” then “PHP” in the next line • echo ‘Hi n PHP’; // prints “Hi n PHP”
  • 7. Curly syntax • In double quoted and heredoc strings, you can have the following : $x[10] = “great”; $x[‘name’] = “strings”; $y = “ This is {$x[10]} ”; // This is great $z = “ {$x[‘name’]} are flexible.”; // strings are flexible.
  • 8. Accessing characters • Strings can be accessed like arrays to get a specific character : $x = “String”; echo $x[0]; // S echo $x[1]; // t echo $x[2]; // r
  • 9. String Operations • Concatenation operator “.”: $x = “Hello ” . “ world”; // Hello world • Concatenating assignment operator : $x = “Hello ”; $x .= “world” // Hello world
  • 10. String Comparison 1. Can compare strings using “==“ operator : if( $x == “Hi” ) echo “yes”; 1. Can use strcmp() built-in function : if( strcmp( $x, “Hi”) == 0 ) echo “yes”; 1. Use strcasecmp() for case insensitive comparisons : if( strcasecmp( “hi”, “Hi”) == 0 ) echo “yes”;
  • 11. String Length The function strlen() returns the length of the string: Example: echo strlen( “A string” ); // 8
  • 12. Searching Strings int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) Returns the numeric position of the first occurrence of needle in the haystack string. Example: $mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); // 0
  • 13. Replacing Strings mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. Example: echo str_replace( “Hi”, “Hello”, “Hi strings.” ); // Hello strings.
  • 14. Extracting Strings string substr ( string $string , int $start [, int $length ] ) Returns the portion of string specified by the start and length parameters. Example : echo substr('abcdef', 1); // bcdef echo substr('abcdef', 1, 3); // bcd echo substr('abcdef', 0, 4); // abcd echo substr('abcdef', 0, 8); // abcdef echo substr('abcdef', -1, 1); // f
  • 15. Splitting Strings array explode ( string $delimiter , string $string [, int $limit ]) Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. Example : $string = “this is a string"; $pieces = explode(" ", $string); var_dump($pieces); // prints an array containing the parts
  • 16. Joining Strings string implode ( string $glue , array $pieces ) Join array elements with a glue string. Example : $array = array( “this”, “is”, “a”, “string” ); $string= implode(" ", $array); echo $string; // this is a string
  • 17. Exercise Write a PHP function that reverses the string words, so If we have a string like this : this is the php strings lesson The function should return this : lesson strings php the is this
  • 18. Exercise solution <?php function reverse_words($string){ $result = ""; $exploded = explode(" ", $string); $reversed = array_reverse($exploded); $result = implode(" ", $reversed); return $result; } reverse_words( "this is the php strings lesson" ); ?>
  • 19. Formatting Strings string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' ) This function formats a number according to the passed arguments. Example : $number = 1234.5678; $english_format_number = number_format($number, 2, '.', ''); // 1234.57
  • 20. Formatting Strings string sprintf ( string $format [, mixed $args [, mixed $... ]] ) Returns a string produced according to the formatting string format. Example printf(“My name is %s and my age is %d", “John”, 20 ); // My name is John and my age is 20 For a complete list of details, visit : http://php.net/manual/en/function.sprintf.php
  • 21. Regular Expressions • Regular expressions ( Regex ) provide flexible means for matching strings of text. • For example : How can I check whether the user supplied a valid e- mail or not ? • There should be something that tells : Is the string like some characters/digits then @ then some characters/digits then .com ??? Here comes the regex.
  • 22. Meta Characters Meta characters are characters the have some special meanings in the regex pattern. Character Description general escape character with several uses ^ assert start of subject (or line, in multiline mode) $ assert end of subject (or line, in multiline mode) . match any character except newline (by default) [ start character class definition ] End character class definition | start of alternative branch ( Start of sub pattern ) End of sub pattern
  • 23. Meta Characters Character Description ? 0 or 1 * 0 or more + 1 or more { Start min/max number of occurrences } End min/max number of occurrences ^ negate the class, but only if it is the first character - Character range
  • 24. Character Classes Character classes define the type of characters in the regex pattern. Class Description d Matches any numeric character - same as [0-9] D Matches any non-numeric character - same as [^0-9] s Matches any whitespace character - same as [ tnrfv] S Matches any non-whitespace character - same as [^ tnrfv] w Matches any alphanumeric character - same as [a-zA-Z0-9_] W Matches any non-alphanumeric character - same as [^a-zA-Z0-9_]
  • 25. Regex Examples Regular expression (pattern) Match (Subject ) Not match Comment world Hello world Hello Jim Match if the pattern is present anywhere in the subject ^world world class Hello world Match if the pattern is present at the beginning of the subject world$ Hello world world class Match if the pattern is present at the end of the subject /world/i This WoRLd Hello Jim Makes a search in case insensitive mode ^world$ world Hello world The string contains only the "world" world* worl, world, worlddd wor There is 0 or more "d" after "worl" world+ world, worlddd worl There is at least 1 "d" after "worl"
  • 26. Regex Examples Regular expression (pattern) Match (Subject ) Not match Comment world? worl, world, worly wor, wory There is 0 or 1 "d" after "worl" world{1} world worly There is 1 "d" after "worl" world{1,} world, worlddd worly There is 1 ore more "d" after "worl" world{2,3} worldd, worlddd world There are 2 or 3 "d" after "worl" wo(rld)* wo, world, worldold wa There is 0 or more "rld" after "wo" earth|world earth, world sun The string contains the "earth" or the "world"
  • 27. Regex Examples Regular expression (pattern) Match (Subject ) Not match Comment w.rld world, wwrld wrld Any character in place of the dot. ^.{5}$ world, earth sun A string with exactly 5 characters [abc] abc, bbaccc sun There is an "a" or "b" or "c" in the string [a-z] world WORLD There are any lowercase letter in the string [a-zA-Z] world, WORLD, Worl12 123 There are any lower- or uppercase letter in the string [^wW] earth w, W The actual character can not be a "w" or "W"
  • 28. Regex Functions int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) Searches subject for a match to the regular expression given in pattern. It will stop by the first occurrence of the pattern. Example: $x = preg_match( “/php*/”, “phpppp”, $result ); // returns 1 var_dump($result); // array(1) { [0]=> string(6) "phpppp" }
  • 29. Regex Functions int preg_match_all ( string $pattern , string $subject , array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]] ) Searches subject for a match to the regular expression given in pattern. It gets all the occurrences of the pattern in the string. Example: $x = preg_match_all( “/php/”, “phpp phpzz”, $result ); // returns 1 var_dump($result); // array(1) { [0]=> array(2) { [0]=> string(3) "php" [1]=> string(3) "php" } }
  • 30. Regex Functions mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) Searches subject for matches to pattern and replaces them with replacement. Example: $x = preg_replace( “/php*/”, “hi” ,“phpp phppz”); echo $x ; // hi hiz
  • 31. Exercise Write a PHP snippet that checks whether the user has entered a valid email or not ( the email should end with a .com ).
  • 32. Exercise Solution <?php $email = "myemail1@example.com"; if(preg_match("/[w]+@[w]+.com/", $email) == 1 ) echo "Valid email"; else echo "Invalid email"; ?>
  • 33. More info about Regex For more info about regular expressions, please visit : http://www.php.net/manual/en/reference.pcre.pattern.syntax.p
  • 34. Assignment 1- Write a function that calculates the number of the words a string has. 2- Write a PHP script that matches the following phone numbers : 718 498 1043 718 198-1043
  • 35. What's Next? • Web Programming.