DEV Community

Cover image for The fastest method for string replacement in PHP
Amburi Roy
Amburi Roy

Posted on • Originally published at leetcode.com

The fastest method for string replacement in PHP

[No BS, only code]

Exploring different ways of replacing strings to determine the fastest method for string replacement:

Used Language

  • PHP

Problem

A defanged IP address replaces every period "." with "[.]".

Solution

1. str_replace

Replace all occurrences of the search string with the replacement string

function defangIPaddr($address) {
    return str_replace('.', '[.]', $address);
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • 62 / 62 test cases passed.
  • Status: Accepted
  • Runtime: 6 ms
  • Memory Usage: 18.9 MB

2. str_ireplace

A case-insensitive version of str_replace

function defangIPaddr($address) {
    return str_ireplace('.', '[.]', $address);
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • 62 / 62 test cases passed.
  • Status: Accepted
  • Runtime: 0 ms
  • Memory Usage: 19.1 MB

3. preg_replace

Perform a regular expression search and replace

function defangIPaddr1($address) {
    return preg_replace('/\./', '[.]', $address);
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • 62 / 62 test cases passed.
  • Status: Accepted
  • Runtime: 5 ms
  • Memory Usage: 19.4 MB

4. implode - explode

Join array elements with a string

function defangIPaddr2($address) {
    return implode('[.]', explode('.', $address));
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • 62 / 62 test cases passed.
  • Status: Accepted
  • Runtime: 5 ms
  • Memory Usage: 19 MB

Conclusion

  • 😱 Implode-Explode takes less runtime than 'str_replace'.
  • 'str_replace' show lower memory usage compared to other string methods.

Feel free to share your thoughts! :)

Top comments (0)