Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.