Rickos
Rickos

Reputation: 45

Regex Match Replace

Im trying to figure out a regex pattern that will look through array below and replace any matching that has a '+' in it with emtpy/null, so if it has a positive number in it then make it null.

thanks for the help. Im still learning.

Array (
[0] => IND: -3
[1] => NYJ: +0
[2] => BAL: +3
[3] => CLE: +6
[4] => WSH: +5
[5] => DET: -2.5
[6] => ATL: +0
[7] => ARI: -7
[8] => OAK: +7
)

$pattern = '/(?<!A-Z\:)\+/i';
$replacement = '';
$replaced = preg_replace($pattern, $replacement, $line

Upvotes: 2

Views: 106

Answers (6)

Rickos
Rickos

Reputation: 45

For extra credit, how would i go about stripping the team names followed by '+'. the array looks like this.

 Array
(
[0] => IND: -3
TEN: +3
[1] => NYJ: -1
BUF: +1
[2] => BAL: +3
CHI: -3
[3] => CLE: +6
CIN: -6
[4] => WSH: +4.5
PHI: -4.5
[5] => DET: -2.5
PIT: +2.5
[6] => ATL: +1
TB: -1
[7] => ARI: -8.5
JAX: +8.5
[8] => OAK: +9
HOU: -9
[9] => SD: -1.5
MIA: +1.5
[10] => SF: +3
NO: -3
[11] => GB: +4.5
)

Upvotes: 0

hwnd
hwnd

Reputation: 70722

Another solution you could use.

foreach ($array as $k => $v) {
   if (preg_match('/\+/', $v)) {
     unset($array[$k]);
   }
}

Output

Array
(
    [0] => IND: -3
    [5] => DET: -2.5
    [7] => ARI: -7
)

See working demo

Upvotes: 1

CrayonViolent
CrayonViolent

Reputation: 32532

array_walk($array, function(&$v){
  $v = (strpos($v,'+')!==false)? null : $v;
});

Upvotes: 2

Marty
Marty

Reputation: 39458

You don't need to go as far as regex for this problem; strpos will tell you if theres a + in the string. With that said, you can remove those occurences using array_filter like this:

$result = array_filter($array, function($i)
{
    return strpos($i, '+') === false;

});

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

Setting to null will unset it, so:

$array = preg_grep('/\+/', $array, PREG_GREP_INVERT);

Upvotes: 4

user764357
user764357

Reputation:

Regexes work on strings, not arrays. Looping through the array, performing integer comparison and reassigning the value back would probably be quicker and simpler.

Upvotes: 1

Related Questions