Question: I'm working on a PHP project where I've to constantly analyse a MySQL query. The problem is that sometimes, this query has more than 1000 chars and I have to break it down manually so I can read it. 

Is there a way to add `<br>` in this string before every uppercase word?  

For example, this query:

```
SELECT  Cid0.*, Cid1.*, CId2.*, CId3.*  FROM `users_cars_brands` CId0  LEFT JOIN  `cars` CId1  ON CId0.cars_id = CId1.id  LEFT JOIN  `cars_texts` CId2  ON CId1.id = CId2.cars_id  LEFT JOIN  `cars_medias` CId3 WHERE CId0.users_cars_id = 1;

```

Would become: 

```
SELECT  Cid0.*, Cid1.*, CId2.*, CId3.*  
FROM `users_cars_brands` CId0  
LEFT JOIN  `cars` CId1  
ON CId0.cars_id = CId1.id  
LEFT JOIN  `cars_texts` CId2  
ON CId1.id = CId2.cars_id  
LEFT JOIN  `cars_medias` CId3 
WHERE CId0.users_cars_id = 1;

```

I've tried to find a way to make it in Regex but I don't know if it is possible.

Answer: 
I've found an incredibly useful PHP class created by [JDorn](https://github.com/jdorn) called [sql-formatter](https://github.com/jdorn/sql-formatter). 

Here is an example of the input and output: 

Input: 

```
SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10

```

Output: 

[![enter image description here](https://i.stack.imgur.com/fzcfV.png)](https://i.stack.imgur.com/fzcfV.png)
You can actually look for *positions* with regular expressions, too. Here, no character is consumed, instead the engine looks for the correct position which can be used to insert something (in your case a newline character). The following regex uses a lookahead and some alternatives (which can be expanded as well):

```
<?php
$sql = "SELECT  Cid0.*, Cid1.*, CId2.*, CId3.*  FROM `users_cars_brands` CId0  LEFT JOIN  `cars` CId1  ON CId0.cars_id = CId1.id  LEFT JOIN  `cars_texts` CId2  ON CId1.id = CId2.cars_id  LEFT JOIN  `cars_medias` CId3 WHERE CId0.users_cars_id = 1;";
$regex = '~
        (?=(?:FROM|LEFT|ON|WHERE))
        # search for a place where one of the words follow immediately
        ~x';
$sql = preg_replace($regex, "\n", $sql);
echo $sql;

/* produces:
    SELECT  Cid0.*, Cid1.*, CId2.*, CId3.*  
    FROM `users_cars_brands` CId0  
    LEFT JOIN  `cars` CId1  
    ON CId0.cars_id = CId1.id  
    LEFT JOIN  `cars_texts` CId2  
    ON CId1.id = CId2.cars_id  
    LEFT JOIN  `cars_medias` CId3 
    WHERE CId0.users_cars_id = 1;
*/

?>

```