Regular Expression to Change Text Domains

I found myself in a situation where I had to change my text domain on WordPress. I changed it from a single word to hyphen separated (example: foo to foo-bar). Like a dummy, my first call was to just do a Replace All. That didn’t work, because convention in WordPress is to put a namespace in front of functions, and my namespace was foo. As you know, hyphens do not belong in PHP functions.

If you ever find yourself in a similar situation, I wanted to share a RegEx trick that may help save you time, just as I hope it will save me some time when I find myself in this situation again.

(__\((?:[^'"]*)(?:\'|\")(?:[^']*)(?:\'|\"),(?:[^'"]*))(?:[^'"]*)(?:\'|\")<OLD NAMESPACE>((?:\'|\")(?:[^'"]*)\))

(Replace [YOUR OLD NAMESPACE] with the namespace you want to replace).

From there, it’s as simple as replacing your match. This regular expression makes it easy to do this by wrapping your replace with your first match and your second match.

In vim, you could simply type this:

:%s/\(__(\(?:[^'"]*\)\(?:\'|\"\)\(?:[^']*\)\(?:\'|\"\),\(?:[^'"]*\)\)\(?:[^'"]*\)\(?:\'|\"\)<YOUR OLD NAMESPACE>\(\(?:\'|\"\)\(?:[^'"]*\))\)/\<NEW NAMESPACE>\2

(Note that you want to replace the text in brackets with the text you want to find and replace).

Leave a Reply