Advertisement
Plepzz

str_replace

May 14th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1. Usage:
  2. First param should be a field in a mysql query or a join condition
  3. $this->_stick_field('table.fieldname = table2.fieldname2');
  4.  
  5. private function _stick_field($field)
  6. {
  7.     if (!preg_match('/`/', $field) && ($field != '*') && $this->_auto_sticks)
  8.     {
  9.         // Match any table names associated with a field name.
  10.         if (preg_match('/^[a-zA-Z0-9\-_\*]+\.[a-zA-Z0-9\-_\*]+$/', $field))
  11.         {
  12.             $_arr_field = explode(".", $field);
  13.             foreach ($_arr_field as $k => $v)
  14.             {
  15.                 if ($v != '*')
  16.                 {
  17.                     $_arr_field[$k] = '`'.$v.'`';
  18.                 }
  19.             }
  20.             return implode(".", $_arr_field);
  21.         }
  22.  
  23.         /**
  24.          * This is primarily used for join conditions.
  25.          * The following tries to match as many table and field
  26.          * names as posible, then splits them up, add backsticks
  27.          * puts them togheter and replace the original string
  28.          * with the formatted one.
  29.          */
  30.         preg_match_all('/([a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+)/', $field, $match);
  31.  
  32.         // Did we find any match?
  33.         if (!empty($match[0]))
  34.         {
  35.             $_replace = array();
  36.             // Search through the matches
  37.             foreach ($match[0] as $k => $v) {
  38.                 $_arr_field = explode('.', $v);
  39.                 $_buffer = array();
  40.                 // Wrap field/table with backsticks
  41.                 foreach ($_arr_field as $value)
  42.                 {
  43.                     if ($value != '*')
  44.                     {
  45.                         // Add the formatted field/value to the buffer
  46.                         $_buffer[] = "`".$value."`";
  47.                     }
  48.                 }
  49.                 // Store the formatted field/value in the replace var
  50.                 $_replace[$k] = implode('.', $_buffer);
  51.             }
  52.             // Replace the original string with the formatted string
  53.             return str_replace($match[0], $_replace, $field);
  54.  
  55.         } else {
  56.             return '`'.$field.'`';
  57.         }
  58.     }
  59.     return $field;
  60. } // _stick_field($field)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement