Add underscore before capital letters

How to add underline (_) infront of all uppercase letters in a string?

PrintHello will become: Print_Hello

PrintHelloWorld will be next: Print_Hello_World

+4
source share
2 answers

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
+5
source

You also had the requirement to ignore the first uppercase letter, so I put a “negative appearance” to check if it was not at the beginning of the line or not. The beginning of the line is represented by the ^ character.

<?php
$string = 'PrintHelloWorld';
$pattern = '/(?<!^)([A-Z])/';
$replacement = '_$1';
echo preg_replace($pattern, $replacement, $string);
?>

: http://ideone.com/HvjfWW

+1

All Articles