0

I need to write a function that takes in a long string that is a sql command and searches for an equal sign goes back to the word before it and adds "post." before it.

Example:

input:

$sqlFilter = "WHERE sport = 'Hockey' AND team = 'New York Rangers';

Output:

$sqlFilter = "WHERE post.sport = 'Hockey' AND post.team = 'New York Rangers';
2
  • just looking for some sudo code on where to start.. I can scan the whole string with for loops find the equal character and then go back and replace using the spaces as markers but there might and probably is a better way Commented Jul 6, 2016 at 23:08
  • A regex pattern may work... probably not going to be battle proof though. regex101.com/r/rK1qP5/1 Commented Jul 6, 2016 at 23:15

2 Answers 2

2

You don't need to write any function because you have a preg_replace.

You need to add this code

$newSqlFilter = preg_replace('/([^(\s]*?)[ ]{0,}=/', 'post.\0', $sqlFilter);

And the other thing - close your query string with " character.

Sign up to request clarification or add additional context in comments.

2 Comments

^ see this is why I asked.. my php knowledge is basically limited to C knowledge. Thank you.
.. I am not so great with regex and actually have a bracket at the start and end of the filter variable so getting an error like "WHERE post.(sport = 'Hockey' AND post.team = 'New York Rangers') work around to get it on the inside of the bracket?
2

You can use regular expression search pattern, using function preg_replace_callback(), that accepts callback method name to make replacement. You use expression to find desired pattern and use callback method to make replacement.

Read more about here http://php.net/manual/en/function.preg-replace-callback.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.