How can I replace a set of words that look like:
SomeText
to
Some_Text
?
$s1 = "ThisIsATest";
$s2 = preg_replace("/(?<=[a-zA-Z])(?=[A-Z])/", "_", $s1);
echo $s2; // "This_Is_A_Test"
Explanation:
The regex uses two look-around assertions (one look-behind and one look-ahead) to find spots in the string where an underscore should be inserted.
(?<=[a-zA-Z]) # a position that is preceded by an ASCII letter
(?=[A-Z]) # a position that is followed by an uppercase ASCII letter
The first assertion makes sure that no underscore is inserted at the start of the string.