0

I have this kind of output: 1342&-4&-6 And it could be more times or less: 1342&-4 (I need to replace it with: 1342,1344) 1340&-1&-3&-5&-7 (I need to replace it with: 1340,1341,1343,1345,1347)

I've tried to use preg_match but with no success, Can someone help me with that?

Thanks,

6
  • the replacement rules are not clear (to me at least) Commented Dec 11, 2016 at 20:05
  • 1342&-4&-6 --> 1342 and 1344 and 1346 Commented Dec 11, 2016 at 20:10
  • 1340&-1&-3&-5&-7 --> 1340 and 1341 and 1343 and 1345 and 1347 Commented Dec 11, 2016 at 20:12
  • 1342&-4 --> 1342 and 1344 Commented Dec 11, 2016 at 20:12
  • so if you had sting input of "1342&-4" you would get 2 stings returned "1342" and "1344"? Commented Dec 11, 2016 at 20:14

2 Answers 2

1
<?php



//so if you had sting input of "1342&-4" you would get 2 stings returned "1342" and "1344"? 

//1340&-1&-3&-5&-7 --> 1340 and 1341 and 1343 and 1345 and 1347

//$str="1342&-4";
$str="1340&-1&-3&-5&-7";
$x=explode('&-',$str);

//print_r($x);

foreach ($x as $k=> $v){
    if($k==0){
        //echo raw
        echo $v."<br>";
    }else{
    //remove last number add new last number 
    echo substr($x[0], 0, -1).$v."<br>"; 
    }
}

output:

1340
1341
1343
1345
1347

i used <br> you can use what ever you need or add to a new variable(array)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks guys, both of your answers are good but Dagon's suggestion was more compatible to my code so I'm going to use it. thanks a lot
@K.D dont forget to accept the answer: stackoverflow.com/help/someone-answers
@Dagon, sorry about off-topic but, what obsession do you have with "potatoes"?
1
$array = explode('&-', $string);

$len = count($array);

for($i=1; $i<$len; $i++)

    $array[$i] += $array[0]  / 10 * 10;

var_dump(implode(' ', $array));

1 Comment

It works - but a one-liner explanation to go with your code would be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.