...

View Full Version : remove number from string



docock
06-22-2010, 12:04 AM
Let's say I've got a string like this:

$string="4,5,10,3,11,12,1,2,9,8";

which line do I need if I want to remove one of those numbers (inluding the comma behind it) for example 11?

_Aerospace_Eng_
06-22-2010, 12:36 AM
This might help.

<?php
// initial string
$string="4,5,10,3,11,12,1,2,9,8";

// we explode at the comma to put them into an array
$arr = explode(",",$string);

// this is the value we want to find
$val = 11;

// we get the key of that value, this could fail if there is more than one key.
// I think it just returns the first one.
$key = array_search($val,$arr);

// we do a print_r to see the values in the array initially
echo '<pre>';
print_r($arr);

// now we remove the part of the array that contained the value we found
unset($arr[$key]);

// we need to reindex the array
$arr = array_values($arr);

// now we do a print_r again to print out the new array
print_r($arr);
echo '</pre>';

// we can implode to create our string again.
$string = implode(",",$arr);

// we echo out our new string.
echo $string;
?>
There might be an easier way but that is all I can think of right now.

docock
06-22-2010, 12:58 AM
Thanks for replying. That's a lot of code...
Hope someone knows a shorter version before I'm gonna implement

Keleth
06-22-2010, 05:24 AM
If the number is only showing up once and you know there will be a comma before it, you could use


str_replace(',11', '', $string);

You can also use regex.

You do realize a part of the code provided to you above could be removed... its used to display the array as is so you can see whats going on.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum