This can be done using negative lookahead:
$str = 'PrintHelloWorld';
$repl = preg_replace('/(?!^)[A-Z]/', '_$0', $str);
OR using positive lookahead:
$repl = preg_replace('/.(?=[A-Z])/', '$0_', $str);
OUTPUT:
Print_Hello_World
Update: Even easier to use: (thanks to @CasimiretHippolyte)
$repl = preg_replace('/\B[A-Z]/', '_$0', $str);
\B matches, if not at the word boundary
source
share