1

Suppose I have a string:

$str="1,3,6,4,0,5";

Now user inputs 3.

I want that to remove 3 from the above string such that above string should become:

$str_mod="1,6,4,0,5";

Is there any function to do the above?

3
  • 3
    str_replace()? Thats a good start. Also preg_replace() Commented Apr 16, 2015 at 5:09
  • 4
    you can use first explode , unset , implode , str_replace() etc. Read about them and use as per your requirement. Commented Apr 16, 2015 at 5:11
  • 4
    why users are upvoting this question? Commented Apr 16, 2015 at 5:13

3 Answers 3

4

You can split it up, remove the one you want then whack it back together:

$str = "1,3,6,4,0,5";
$userInput = 3;

$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));

echo implode(',', $result); // 1,6,4,0,5

Bonus: Make $userInput an array at the definition to take multiple values out.

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

1 Comment

That's actually pretty clever. +1
2
preg_replace('/\d[\D*]/','','1,2,3,4,5,6');

in place of \d just place your digit php

2 Comments

Regex is not needed in this situation
wrong its less lines, solves commo or no comma problem solves removing a whole 3 not a 3 from 33 . And exploding parsing then intersecting arrays must be more resource waste
2

If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:

$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
    unset($components[$idx]);
}
$string = implode(',', $components);

The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.

Comments

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.