Ste
Ste

Reputation: 1520

Replace a whole integer match in a delimited string and a maximum of one of its adjacent commas

I have this string:

525,294,475,215,365,745

I need to remove 475 ...and its preceding comma.

If I need to remove the first number (and there's more than one number in the string), I need to remove the following comma.

How can I do this? A regular expression?

Upvotes: -1

Views: 131

Answers (6)

mickmackusa
mickmackusa

Reputation: 47864

Using a regex with word boundaries and a conditional match expression will afford a way to remove the whole integer match and only one of its neighbor commas (not both) without exploding and re-imploding.

Code: (Demo)

echo preg_replace('#(,)?\b' . preg_quote($find) . '\b(?(1)|,?)#', '', $string);
  • If there is a comma before the whole number match, then that comma will be matched and removed.
  • If there is no comma before the whole string match, then the optional comma will be matched and removed.

This kind of operation, however, indicates that you might be using a suboptimal data type to manage what seems more appropriately held in an array.

Upvotes: 0

yvoyer
yvoyer

Reputation: 7516

function filterValue($index, &$a) 
{
    $key = array_search($index, $a);
    if ($key != false) {
        unset($a[$key]);
    }
}


// Original data
$data = "525,294,475,215,365,745";
$data = explode(',', $data);

filterValue('475', $data);
$output = implode(',', $data);

Upvotes: 0

Donald
Donald

Reputation: 1738

Here's a regular expression:

$s = "525,294,475,215,365,745";
$s = preg_replace(',?475', '', $s);

Upvotes: 1

jwegner
jwegner

Reputation: 7403

<?php
$bigString = "525,294,475,215,365,745";
$pos = strpos($bigString, ",");
while($pos != false) {
  $newString .= substr($bigString, 0, $pos);
  $bigString = substr($bigString, $pos + 1);
  $pos = strpos($bigString, ",");
}
echo $newString;
?>

Upvotes: 0

Ben
Ben

Reputation: 62356

$newStr = str_replace(',475', '525,294,475,215,365,745');

Or the less error prone way:

$new = array();
$pieces = explode(',', '525,294,475,215,365,745');
foreach ($pieces as $piece) {
   if ($piece != 475) {
      $new[] = $piece;
   }
}

$newStr = implode(',', $new);

Upvotes: 2

cdhowie
cdhowie

Reputation: 168958

$data = "525,294,475,215,365,745";

$parts = explode(',', $data);

for ($i = 0; $i < count($parts); $i++) {
    if ($parts[$i] == 475) {
        unset($parts[$i]);
    }
}

$newdata = join(',', $parts);

Upvotes: 0

Related Questions