How to Insert Space Before Capital Letters in a String using PHP

The Regular Expressions are the easiest option to change the characters format based on the specific pattern. You can change the word format in a string using PHP with Regex. In the example code snippet, we will show you how to insert space before capital letter in a string using PHP.

Sometimes the words are bunched together in a string, and you want to separate the words with spaces. In this case, you need to put a space in front of each word for differentiating the words in the string. Using the PHP preg_replace() function, you can add space in front of uppercase character in a string.

The following code separates the words by spaces and inserts space before the capital letter in a string using preg_replace() in PHP.

$string = 'TcmHackWebsite';
$words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $string);


Tcm Hack Website