-1

我对 PHP 和这个论坛很陌生。我不知道我的问题是否适合这个论坛。

我有一个字符串$filter=([operator] = 'IDEA') AND ([type] = 'R,T'); ,但在这个字符串中有一个值 [type] 的动态值,这意味着值 [type]='R,T' 可能是 [type]='R,T,P' ...... ……

现在对于 [type] 中的每个字符内容应该更改为 -

([operator] = 'IDEA') AND ([type] ='R' OR [type] = 'T')

或者

([operator] = 'IDEA') AND ([type] ='R' OR [type] = 'T' OR [type] = 'P')

…………………………………………………………………………………………………………

为此,我编写了一个小代码,大约需要 1 天。

$text = explode("[type] =",$filter);
$myreplacetext = "[type] = ".$text[1];
$text2 = preg_replace('/[^a-zA-Z0-9_ %\[\]\.,]/s', '', $text[1]);
$string = explode(",", $text2);;
$i=0;
foreach($string as $value){
    $value = trim($value);
    if($i==0)$mynewtext = "'".$value."'";
    else $mynewtext = $mynewtext." OR [type] = '".$value."'";
    $i++;
}
$mynewtext = $mynewtext.")";
$filter = str_replace($text[1],$mynewtext,$filter);

请任何人指导我以简单的方式编写此代码

4

1 回答 1

1

好的。试试这个代码。有任何问题,请随时在这里发表评论。

    $filter = "([operator] = 'IDEA') AND ([type] = 'R,T,P')";
    $text = explode("[type] =",$filter);
    $firstPart = $text[0];
    $text2 = preg_replace('/[^a-zA-Z0-9_ %\[\]\.,]/s', '', $text[1]);

    // now:
    // $firstPart sholud be like '([operator] = 'IDEA') AND ('
    // $text2 should be like 'a,b,c'
    $string = explode(",", $text2);
    $typeList = array();
    foreach ($string as $value)
    {
        $value = trim($value);
        if (!$value)
        {
            continue;
        }
        $typeList[] = "[type] = '$value'";
    }
    $typeStr = implode(' OR ', $typeList);

    // $firstPart sholud be like '([operator] = 'IDEA') AND ('
    // $typeStr should like: [type] ='R' OR [type] = 'T' OR [type] = 'P'

    // so the result should be:
    $filter = $firstPart . $typeStr . ')';
    echo $filter;
    // the output:  ([operator] = 'IDEA') AND ([type] = 'R' OR [type] = 'T' OR [type] = 'P')
于 2013-07-20T03:37:56.427 回答