SlideShare a Scribd company logo
1 of 17
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
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
King Hom
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
ADARSH BHATT
 

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

Recently uploaded (20)

WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 

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