开发者

Replace all that not contains .. ER

开发者 https://www.devze.com 2023-03-06 23:32 出处:网络
Hey guys, how i can replace all index of array that not contains quant in index name ? i trying this: for( $i = 0; $i < count( $query ); ++$i ){

Hey guys, how i can replace all index of array that not contains quant in index name ? i trying this:

for( $i = 0; $i < count( $query ); ++$i ){
          foreach( $query[$i] as $index => $data ){
               echo preg_replace( '/(?!quant(.*)$)/', '', $index ), '<开发者_JAVA技巧;br />';
          }
}


It sounds like all you want is indexes filtered which do not contain "quant". If so then a simple if will do, and there's no need for a regex or any string manipulation whatsoever:

for ($i = 0; $i < count( $query ); ++$i) {
    foreach ($query[$i] as $index => $data) {
        if (strstr($index, "quant")) {
            echo $index, '<br />';
        }
    }
}


Consider this php code to do this filtering:

$array = array("quant1"=>1, "price1"=>2, "quant2"=>3, "price2"=>4, "quant3"=>3);
$filteredKeys = array_filter(array_keys($array), function ($elem) { return strpos($elem, "quant") !== false; } );
print_r(array_intersect_key($array, array_flip($filteredKeys))); 

OUTPUT

Array
(
    [quant1] => 1
    [quant2] => 3
    [quant3] => 3
)


I think this is the regex you were looking for:

^(?:(?!quant).)+)$

The idea is to apply the lookahead at each position before you consume the next character. Here's another option:

^(?!.*quant).+$

Here the lookahead is applied only once, at the beginning of the string. Starting there, it scans the whole string looking for an instance of quant. If it doesn't find one, the lookahead succeeds, and .+$ goes ahead and gobbles up the whole string.

EDIT: Also notice the start anchor (^) I added. Whatever regex you eventually use, it must be anchored at both ends. Otherwise you'll never be sure you really examined the whole string.

0

精彩评论

暂无评论...
验证码 换一张
取 消