I’m trying to port a script that I wrote in bash some time ago into PHP. One particular line is about escaping all non-alphanumeric characters.
In bash, I was able to do it as a one-liner as follows:
echo "aaa bbb::" | sed 's/\([^a-zA-Z0-9]\)/\\\1/g'
# => aaa\ bbb\:\:
The closest I got in PHP was with this:
echo preg_replace('/([^a-zA-Z0-9])/','\\\','aaa bbb::');
# => aaa\bbb\\
However I’m struggling to reuse my regex group inside preg_replace (I tried \1 and $1).
Can someone help me get this PHP one-liner right please?
1 Answer