6

I need to replace some string in a PHP code to make it look better. What would be the best way to go about that?

3

4 Answers 4

8

The usual suspects would be str_replace and preg_replace.

3
  • 5
    I don't believe it answers the question in regards to which one is the fastest unfortunately.
    – Sebas
    May 12, 2014 at 9:14
  • 2
    As the documentation mentions, str_replace is faster than preg_replace if you just need a simple string replacement. Also the question is vague enough that you cannot give a tailored answer. And in almost all cases the standard functions are sufficient and not a performance bottleneck.
    – Joey
    May 12, 2014 at 11:55
  • 1
    For small parts strtr is faster. I used strtr and str_replace simultaneous. Feb 1, 2021 at 14:09
0
preg_replace

Is a good way to go and uses regular expressions so you have flexibility as to how to do it.

0

If you want to replace a string in a lot of files once (e.g., you have something in your source code which you want to replace), sed might be the right tool for the job.

man sed
1
  • in php? how would you do it? I mean, assuming security is ON and exec is disabled...
    – Sebas
    May 12, 2014 at 9:36
0

It depends. If str_replace works for your case, I think is faster and less memory consumer than preg_replace

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.