Ragen Dazs
Ragen Dazs

Reputation: 2170

PHP regex remove prepend content before dot

I have in PHP an array string which contain stuff like this:

$a = array(
  array('inner' => 'N.person = P.id'),
  array('inner' => 'L.person = P.id'),
  array('left' => 'A.person = P.id AND A.excluded IS NULL')
);

And I want to inform primary key P.id and remove all alias from sql resulting in something like this:

$x = someFunctionThatSanitizeSQL('P.id', $a); 

print_r on $x result:

array(
  array('inner' => 'person = :pk'),
  array('inner' => 'person = :pk'),
  array('left' => 'person = :pk AND excluded IS NULL')
);

Thanks in advance

@edit: miss a typo

Upvotes: 0

Views: 214

Answers (1)

Mara Ormston
Mara Ormston

Reputation: 1856

After doing a str_replace($pkreplace, ':pk', $mystring);, the regex I think you're looking for is something like:

/(?=(^|\w))[A-Z0-9_-]+\./

For example, to clean out each string, you can do

preg_replace('/(?=(^|\w))[A-Z0-9_-]+\./i', '', $mystring);

However, if you are removing the A., L., etc., there may be other issues with your query due to the values no longer being under the database tables and possibly causing ambiguous value errors. Are you certain this is the behavior you want in your queries?

EDIT

A final implementation of your function would look something like (assuming you need arrays):

function someFunctionThatSanitizeSQL($pkreplace, $dataarray) {
  if (!is_array($dataarray))
    return null;
  $retval = array();
  foreach ($dataarray as $key => & $curentry) {
    $curstring = str_replace($pkreplace, ':pk', $curentry);
    $curstring = preg_replace('/(?=(^|\w))[A-Z0-9_-]+\./i', '', $curstring);
    $retval[$key] = $curstring;
  }
  return $retval;
}

Upvotes: 1

Related Questions