Jump to content

SQL Query Regex


Suchy

Recommended Posts

I'm having troubles with a regular expressions.

 

What I want is to replace the begining of a SQL query.

ex.

SELECT * FROM employes ...
SELECT name.employes, id.employes FROM employes ...
SELECT name.employes, id.dept, nr.room FROM ...
....

 

I need to replace anything between SELECT and FROM with

SELECT COUNT(*) AS num_of_rows  FROM

 

<?php
	 echo "old query -> " . $query . "<br><br>";

	 $regex = "/^(SELECT|Select|select)([\s]|[a-zA-Z0-9\.\*-_,]|[\s])+[(FROM|From|from)]/";

	 if (preg_match($regex , $query ))
	 	echo "YES<br>";
	else
		echo "NO<br>"	;

	 $query = preg_replace($regex, "SELECT COUNT(*) AS num_of_rows  FROM ", $query);

	echo "new query -> " . $query . "<br><br>";
?>

 

 

How can I modify my regex inorder for this to work ?

 

 

Link to comment
https://forums.phpfreaks.com/topic/196637-sql-query-regex/
Share on other sites

Thats it, Thanks !

 

But the problem that I had was with newlines and returns.

 

Ex. To keep the query looking clean I had something like this

SELECT name.employes, birhtdate.employes, 
             building.room,  nr.room,
             name.dept, manager.dept,  id.dept,
            ...
FROM ...

Instead of writing it in a single line.

 

This is how I solved the problem

<?php
$query = str_replace("\r" , "" , $query);
$query = str_replace("\n" , "" , $query);
$query = str_replace("\t" , "" , $query);
$regex = "/^SELECT .* FROM/i";

// $regex = "/^SELECT (.|\n|\s|\t|\r)* FROM/i";              <--- this did not work for me
?>

 

 

Once again, thanks for the shorter regex.

Link to comment
https://forums.phpfreaks.com/topic/196637-sql-query-regex/#findComment-1033622
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.