Search and Replace PHP split() with Python
Tuesday, May 4th, 2010A couple of days ago I upgraded to Ubuntu 10.04 which, in turn, upgraded my PHP version from 5.2 to 5.3. In PHP 5.3 they have completely deprecated the use of the split() function in favour of explode(). I did a quick search in my /work directory and it turns out that I have 832 files that are affected by this. All of them need to have split() replaced with explode() or the websites will throw errors every time they encounter it.
Here’s how I did it using an altered Python script I wrote a couple of years ago:
#! /usr/bin/python
import os
import re
mydir = "/home/damian/work"
def doReplace(filePath):
fin = open(filePath, "r")
s = fin.read()
fin.flush()
fin.close()
p = re.compile('(\s|\(|=)split\(')
if p.search(s):
fout = open(filePath, "w")
s = p.sub(r'\1explode(', s)
fout.write(s)
fout.close()
for root, dirs, files in os.walk(mydir):
for f in files:
name, ext = os.path.splitext(f)
if ext == '.php':
doReplace(root + '/' + f)
(**UPDATE** I’ve switched the search and replace to use regular expressions because I found that ‘split()’ can be prefixed by a number of symbols but not others — i.e. don’t replace ‘preg_split()’)
