SlideShare a Scribd company logo
Comparing two string
modification functions
Differences between behaviors of strtr() and
str_replace()
Patrick Maynard | Ixopay
PHPDAY VERONA 2024
1
About me
– Coming from the Symfony world
– Now working remotely for Ixopay, a payment orchestrator based in Vienna
– Ixopay uses Laravel, which I am still relatively new to
– We’re hiring! https://www.ixopay.com/en/company/careers
– Social media links: https://patrickmaynard.com
2
An introduction to str_replace()
– Replaces substrings, via multiple passes if needed
– Good for real-world scenarios that are unpredictable, but where regexes are
overkill
– Case-insensitive variant is str_ireplace()
3
str_replace() example one
– This example uses the method’s simple format, specifying exactly one
replacement pair.
$adjective = 'schön';
$converted = str_replace('ö', 'oe', $adjective);
//Gives us 'schoen'
4
str_replace() example two
– Can use an array to specify more complex replacements
$streetName = 'Schönwald Straße';
$originals = [ 'ä', 'ö', 'ü', 'Ä', Ö', 'Ü', 'ß'];
$replacements = ['ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss' ];
$cleaned = str_replace($originals, $replacements, $streetName);
//Gives us 'Schoenwald Strasse'
5
An introduction to strtr()
– Does ONE round of replacement, directly translating (hence the "tr") one
character or substring into another
– Has two possible input formats:
strstr(string $myString, string $from string $to)
or
strstr(string $myString, array $mappings)
– Not to be confused with strstr()
6
strtr() example one
– This example uses the simple format, specifying exactly one replacement pair.
$adjective = 'schön';
$cleaned = strtr($adjective, 'ö', 'oe');
//Gives us 'schoen'
7
strtr() example two
– The array format can work better for larger sets.
$streetName = 'Schönwald Straße';
$mappings = [ 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'Ä' => 'Ae' => 'Ö' => 'Oe', 'Ü' =>
'Ue', 'ß' => 'ss' ];
$cleaned = strtr($streetName, $mappings);
//Gives us 'Schoenwald Strasse'
8
Differences in behavior
… so these are basically the same.
9
Differences in behavior
… so these are basically the same.
… right?
No.
If given an array of mappings,
str_replace() replaces inside the
replacements, going from left to right,
leading to sometimes counterintuitive
results. So this code …
$output = [];
$myString = 'WordOne WordTwo WordThree
WordFour WordFive WordSix';
$mappings = [
'WordOne' => 'WordTwo',
'WordTwo' => 'WordThree',
'WordThree' => 'WordFour',
'WordFour' => 'WordFive',
'WordFive' => 'WordSix',
'WordSix' => 'WordSeven'
];
$output['str_replace_results'] = str_replace(
array_keys($mappings),
array_values($mappings),
$myString);
$output['strtr_results'] = strtr($myString, $mappings);
print_r($output);
10
Differences in behavior (continued)
… yields this output:
[str_replace_results] => WordSeven WordSeven WordSeven WordSeven
WordSeven WordSeven
[strtr_results] => WordTwo WordThree WordFour WordFive WordSix
WordSeven
11
Differences in behavior (continued)
There's more.
– The str_replace() function can take in a subject array, allowing replacement of
multiple (string-formatted) array values at once in different parts of the array
12
Differences in behavior (continued)
There's more.
– The str_replace() function can take in a subject array, allowing replacement of
multiple (string-formatted) array values at once in different parts of the array
– When you do this (or even use a simple string replacement), you can also give a
fourth argument: An int variable that will be modified by reference to hold the
number of replacements performed. So, for example …
13
Differences in behavior (continued)
$result = [];
$count = 0;
$inputStringsExample = ['EUR,USD','USD,EUR'];
$abbreviations = ['EUR', 'USD'];
$acceptedCurrencies = ['Euros', 'U.S. dollars'];
$fixed = str_replace($abbreviations,
$acceptedCurrencies, $inputStringsExample,
$count);
print_r($inputStringsExample);
print $count;
… yields this output:
Array
(
[0] => EUR,USD
[1] => USD,EUR
)
4
14
Differences in behavior (continued)
You can even feed str_replace() a string for the subject and an array for the
replacement, allowing you to replace a series of identical wildcards in a document
with a sequence of ever-changing values.
(Similar to PDO parameter substitution -- but obviously use that safer, baked-in
PDO behavior instead if working with a database.)
15
Summary
– Use str_replace() with caution, as it may do multiple sequential replacements
– If that's a problem (and you don't need to count replacements), use strtr()
– If you need a count but you don't trust str_replace(), you can use strtr() twice
with a flag value
16
Thank you!
– These slides: https://www.slideshare.net/patrickmaynard3
– Ixopay careers page: https://www.ixopay.com/en/company/careers
– Social media links: https://patrickmaynard.com
17

More Related Content

Similar to Comparing two string modification functions

Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
sana mateen
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
arnold 7490
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
Simon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
Simon Proctor
 
Module7
Module7Module7
Module7
Seid Hussein
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
Raffi Khatchadourian
 
05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.ppt
MuthuMs8
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
Saeid Zebardast
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
DarellMuchoko
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
King Hom
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
Chris Chubb
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
Amirul Azhar
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
Laiby Thomas
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
ADARSH BHATT
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
Sharon Liu
 

Similar to Comparing two string modification functions (20)

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
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
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
Regular expressionsRegular expressions
Regular expressions
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Module7
Module7Module7
Module7
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.ppt
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
regular-expression.pdf
regular-expression.pdfregular-expression.pdf
regular-expression.pdf
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
 
Php Chapter 4 Training
Php Chapter 4 TrainingPhp Chapter 4 Training
Php Chapter 4 Training
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 

Recently uploaded

Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 

Recently uploaded (20)

Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 

Comparing two string modification functions

  • 1. Comparing two string modification functions Differences between behaviors of strtr() and str_replace() Patrick Maynard | Ixopay PHPDAY VERONA 2024 1
  • 2. About me – Coming from the Symfony world – Now working remotely for Ixopay, a payment orchestrator based in Vienna – Ixopay uses Laravel, which I am still relatively new to – We’re hiring! https://www.ixopay.com/en/company/careers – Social media links: https://patrickmaynard.com 2
  • 3. An introduction to str_replace() – Replaces substrings, via multiple passes if needed – Good for real-world scenarios that are unpredictable, but where regexes are overkill – Case-insensitive variant is str_ireplace() 3
  • 4. str_replace() example one – This example uses the method’s simple format, specifying exactly one replacement pair. $adjective = 'schön'; $converted = str_replace('ö', 'oe', $adjective); //Gives us 'schoen' 4
  • 5. str_replace() example two – Can use an array to specify more complex replacements $streetName = 'Schönwald Straße'; $originals = [ 'ä', 'ö', 'ü', 'Ä', Ö', 'Ü', 'ß']; $replacements = ['ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss' ]; $cleaned = str_replace($originals, $replacements, $streetName); //Gives us 'Schoenwald Strasse' 5
  • 6. An introduction to strtr() – Does ONE round of replacement, directly translating (hence the "tr") one character or substring into another – Has two possible input formats: strstr(string $myString, string $from string $to) or strstr(string $myString, array $mappings) – Not to be confused with strstr() 6
  • 7. strtr() example one – This example uses the simple format, specifying exactly one replacement pair. $adjective = 'schön'; $cleaned = strtr($adjective, 'ö', 'oe'); //Gives us 'schoen' 7
  • 8. strtr() example two – The array format can work better for larger sets. $streetName = 'Schönwald Straße'; $mappings = [ 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'Ä' => 'Ae' => 'Ö' => 'Oe', 'Ü' => 'Ue', 'ß' => 'ss' ]; $cleaned = strtr($streetName, $mappings); //Gives us 'Schoenwald Strasse' 8
  • 9. Differences in behavior … so these are basically the same. 9
  • 10. Differences in behavior … so these are basically the same. … right? No. If given an array of mappings, str_replace() replaces inside the replacements, going from left to right, leading to sometimes counterintuitive results. So this code … $output = []; $myString = 'WordOne WordTwo WordThree WordFour WordFive WordSix'; $mappings = [ 'WordOne' => 'WordTwo', 'WordTwo' => 'WordThree', 'WordThree' => 'WordFour', 'WordFour' => 'WordFive', 'WordFive' => 'WordSix', 'WordSix' => 'WordSeven' ]; $output['str_replace_results'] = str_replace( array_keys($mappings), array_values($mappings), $myString); $output['strtr_results'] = strtr($myString, $mappings); print_r($output); 10
  • 11. Differences in behavior (continued) … yields this output: [str_replace_results] => WordSeven WordSeven WordSeven WordSeven WordSeven WordSeven [strtr_results] => WordTwo WordThree WordFour WordFive WordSix WordSeven 11
  • 12. Differences in behavior (continued) There's more. – The str_replace() function can take in a subject array, allowing replacement of multiple (string-formatted) array values at once in different parts of the array 12
  • 13. Differences in behavior (continued) There's more. – The str_replace() function can take in a subject array, allowing replacement of multiple (string-formatted) array values at once in different parts of the array – When you do this (or even use a simple string replacement), you can also give a fourth argument: An int variable that will be modified by reference to hold the number of replacements performed. So, for example … 13
  • 14. Differences in behavior (continued) $result = []; $count = 0; $inputStringsExample = ['EUR,USD','USD,EUR']; $abbreviations = ['EUR', 'USD']; $acceptedCurrencies = ['Euros', 'U.S. dollars']; $fixed = str_replace($abbreviations, $acceptedCurrencies, $inputStringsExample, $count); print_r($inputStringsExample); print $count; … yields this output: Array ( [0] => EUR,USD [1] => USD,EUR ) 4 14
  • 15. Differences in behavior (continued) You can even feed str_replace() a string for the subject and an array for the replacement, allowing you to replace a series of identical wildcards in a document with a sequence of ever-changing values. (Similar to PDO parameter substitution -- but obviously use that safer, baked-in PDO behavior instead if working with a database.) 15
  • 16. Summary – Use str_replace() with caution, as it may do multiple sequential replacements – If that's a problem (and you don't need to count replacements), use strtr() – If you need a count but you don't trust str_replace(), you can use strtr() twice with a flag value 16
  • 17. Thank you! – These slides: https://www.slideshare.net/patrickmaynard3 – Ixopay careers page: https://www.ixopay.com/en/company/careers – Social media links: https://patrickmaynard.com 17

Editor's Notes

  1. https://docs.google.com/document/d/1pJwiabIbb_R3DgoOwqhOm1Ouq_IqioDnkLDmyD0x4SI/edit