【问题标题】:How to do a exact word replacment in a string using PHP如何使用 PHP 在字符串中进行精确的单词替换
【发布时间】:2015-07-13 21:05:34
【问题描述】:

我在字符串中使用数字作为变量来构造逻辑。

这是我拥有的字符串示例

(1 AND 2)
2  AND   1
(1 AND 2) OR  (3 AND 4)
1 AND (2  OR  3)

然后我有一个看起来像这样的数组

 $this->clause = array(
          '1' => (object) array('fieldId' => 'id',
                                'value' => 1),

          '2' => (object) array('fieldId' => 'cost',
                                'value' => 132),

          '3' => (object) array('fieldId' => 'name',
                                'value' => "Jay's LLC"),

          '4' => (object) array('fieldId' => 'first',
                                'value' => "Mike"),
        );

我正在尝试将字符串(1、2、3 和 4)中的值替换为数组中的相应值。

这就是我的字符串完成后的样子

第一个示例“由于逻辑字符串不包含第 3 和 4 条,因此将在字符串末尾使用 'AND' 逻辑添加两者”

(1 AND 2) becomes
( id = '1' AND cost = '132' ) AND name = 'Jay\'s LLC' AND first = 'Mike'

第二个示例“由于逻辑字符串不包含第 3 和 4 条,因此将在字符串末尾使用 'AND' 逻辑添加两者”

    2  AND   1 becomes
    cost = '132' AND id = '1' AND name = 'Jay\'s LLC' AND first = 'Mike'

第三个例子“由于逻辑字符串不包含第 4 条,那么它将在字符串末尾使用'AND'逻辑添加”

(1 AND 2) OR  (3 AND 4) becomes
( id = '1' AND cost = '132' ) OR (name = 'Jay\'s LLC')

最后一个例子

1 AND (2  OR  3) AND 4 becomes
id = '1' (cost = '132' OR name = 'Jay\'s LLC') AND first = 'Mike'

这是我尝试过的

private function getAllWhereClauseStatements()
{
    $query = '';
    $totalClause = count($this->clause);

    if( $totalClause > 0 ){

        $query .= 'WHERE ';

        if( !empty($this->clauseLogic) ){
            $logic = '';
            $tmpLogic = $this->clauseLogic;
            foreach($this->clause as $key => $cl){
                $tmpLogic .= preg_replace('/\b'.$key.'\b/u', $this->getWhereClause($cl), $tmpLogic);
                $this->clause->isUsed = 1;
            }

            if(! empty($logic) ){
                $query .= ' ( ' . $logic . ' ) ';
            }

            foreach($this->clause as $key => $cl){
                if( !isset($this->clause->isUsed) || !$this->clause->isUsed){
                    $query .= ' AND ' . $this->getWhereClause($cl);
                    $this->clause->isUsed = 1;
                }
            }
        }
    }

    return $query;
}



private function getWhereClause($cl)
{
    return $cl->fieldId . ' = ' . $cl->value;
}

我有 2 个问题需要帮助

  1. 我在$this->clause->isUsed = 1; 行收到“警告:尝试分配非对象的属性”
  2. 我正在尝试处理最后一个示例“即 1 AND (2 OR 3)”我得到以下结果

    1 AND (2 OR 3) 1 AND (2 OR name = 'Jay\'s LLC' ) 1 AND (2 OR 3) 1 AND (2 OR name = 'Jay\'s LLC' ) 1 AND (cost <> '132' OR 3) 1 AND (cost <> '132' OR name = 'Jay\'s LLC' ) 1 AND (cost <> '132' OR 3) 1 AND (cost <> '132' OR name = 'Jay\'s LLC' ) id = '1' AND (2 OR 3) id = '1' AND (2 OR name = 'Jay\'s LLC' ) id = '1' AND (2 OR 3) id = '1' AND (2 OR name = 'Jay\'s LLC' ) id = '1' AND (cost <> '132' OR 3) id = '1' AND (cost <> '132' OR name = 'Jay\'s LLC' ) id = '1' AND (cost <> '132' OR 3) id = '1' AND (cost <> '132' OR name = 'Jay\'s LLC' )

问题似乎是我如何尝试更换工作

如何纠正我遇到的 2 个问题?

已编辑

我通过换行解决了第一个问题

$this-&gt;clause-&gt;isUsed = 1;

到

$this-&gt;clause[$key]-&gt;isUsed = 1;

【问题讨论】:

  • 你想用这个构建 SQL 查询吗?
  • 是的,我正在尝试构建 were 子句
  • 您有什么理由不使用PDO and prepared statement?这似乎是一个更简单的解决方案。
  • 我正在构建一个类,它将生成一个复杂的 SQL 查询(多个连接、多个 where 子句)每个子句都有不同的条件(= > 或 LIKE)它比准备工作要复杂得多声明。
  • @EdHeal,它不应该因为我将查询构建限制为只编写带有索引的查询。此外,动态查询将在从属服务器上执行,以减少主服务器的负载。

标签: php regex string


【解决方案1】:

我发现并解决了问题

private function getAllWhereClauseStatements()
{
    $query = '';
    $totalClause = count($this->clause);

    if( $totalClause > 0 || ! empty($this->baseClientId) ){

        $query .= 'WHERE ';

        if( !empty($this->clauseLogic) ){
            $logic = $this->clauseLogic;
            $charArray = array();
            foreach($this->clause as $key => $cl){
                $charArray[] = $key;
            } 

            $charList = implode(',', $charArray);

            if( !empty($charList) ){
                $wordsCount = str_word_count($logic, 1, $charList);
            } else {
                $wordsCount = str_word_count($logic, 1);
            }

            $words = array_count_values($wordsCount);

            foreach($this->clause as $key => $cl){

                if(isset($words[$key]) && $words[$key] > 0){
                    $logic = preg_replace('/\b'.$key.'\b/u', $this->getWhereClause($cl) , $logic);
                    $this->clause[$key]->isUsed = 1;                    
                }

            }

            if(! empty($logic) ){
                $query .= ' ( ' . $logic . ' ) ';
            }

            foreach($this->clause as $key => $cl){
                if( !isset($cl->isUsed) ){
                    $query .= ' AND ' . $this->getWhereClause($cl);
                    $this->clause[$key]->isUsed = 1;
                }
            }
        }

    }

    return $query;
}

【讨论】:

    【解决方案2】:

    我的印象是你有点把事情复杂化了(留下一个问题,你是否应该尝试通过编写自己的查询构建器来重新发明轮子,并且绝对不会进入离题的性能讨论))。

    考虑以下代码替代方案(伪,未经测试!):

    private function getWhere()
    {
        // only do something if clause and logic are given
        if(empty($this->clause) || empty($this->clauseLogic) {
            return '';
        }
    
        // fetch the required properties so we can safely alter them
        $conditions = $this->clause;
        $logic = $this->clausLogic;
    
        // turn the $conditions objects into SQL strings
        array_walk($conditions, function(&$condition) {
            $condition = $condition->fieldid . '="' . $condition->value . '"';
        });
    
        // append missing conditions to the logic
        foreach ($conditions as $key => $value) {
           if (strpos($logic, $key) === false) {
              $logic .= ' AND ' . $key;
           }
        }
    
        // do the replacement and return
        return 'WHERE ' . strtr($logic, $conditions);
    }
    

    正如我所说,未经测试,但我相信它应该与您尝试使用代码实现的目标相同。而且你必须承认它读起来容易得多(因此本质上更容易调试)。

    【讨论】:

    • 感谢您的回答。我全力以赴让我的代码更好/更干净。我不确定您拥有的逻辑是否也会保留括号的位置,这可能会改变逻辑。我正在尝试测试您的代码,但我在Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in 上收到此错误,我认为 array_walk 之类的不正确
    • 是的,这就是你使用未经测试的代码所得到的(或者至少这是我通常得到的)。 array_walk 确实没有正确关闭,现在修复它。小小的忠告,一个血统 ide 会接受这一点(并且可以在更多方面为您提供帮助)。我自己是 phpstorm 用户,但也有免费的替代品(如 netbeans)。这可能需要一些时间来适应,但从长远来看,它肯定会缩短您的开发时间并减少错误。
    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多