I'm having some issues with str_replace, when trying to automatically put backticks around table- and fieldnames.
Assuming i have the following arrays:
$match = array('rooms.roomID','r_rooms.roomID');
$replace = array('`rooms`.`roomID`','`r_rooms`.`roomID`');
$subject = 'rooms.roomID = r_rooms.roomID';
str_replace($match,$replace,$subject);
The result that I expect is:
`rooms`.`roomID` = `r_rooms`.`roomID`
But instead I'm getting this:
`rooms`.`roomID` = r_`rooms`.`roomID`
However if i change r_rooms to r_ooms, my result is as expected
`rooms`.`roomID` = `r_ooms`.`roomID`
I've tried the same precedure, using preg_replace, but this gives me the same output aswell.
It is correct. First replaced value is rooms.roomID to rooms
.roomID
(2 times) Change order of $match and $replace tables to get expected result
$match = array('r_rooms.roomID','rooms.roomID');
$replace = array('`r_rooms`.`roomID`','`rooms`.`roomID`');
Quick fix would be reordering $match
and $replace
arrays like this...
$match = array('r_rooms.roomID', 'rooms.roomID');
$replace = array('`r_rooms`.`roomID`', '`rooms`.`roomID`');
The problem of the original approach is that str_replace
processes $match
array element by element, at each step trying to cover the whole string - and replaces the found parts immediately.
As rooms.roomID
string 'matches' both [rooms.roomID]
and r_[rooms.roomID]
, and replaces these accordingly, the second iteration will have nothing to do.
As I said, that's only a quick fix. In this case I'd try to use preg_replace
instead, surrounding the actual search with \b
(word boundary anchors).
Then again, with all due respect I smell XY problem here. Aren't you trying to make your own routine for quoteIdentifier
? That was already solved (and asked here a lot of times).