Reputation: 1520
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
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);
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
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
Reputation: 1738
Here's a regular expression:
$s = "525,294,475,215,365,745";
$s = preg_replace(',?475', '', $s);
Upvotes: 1
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
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
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