Jump to content

Best way to remove this string from another string?


Jakez

Recommended Posts

I'm trying to find the simplest (no big function) solution to this, probably could do some kind of regex, but I'm a regex noob.

 

Ok let's say I have a string of ID's like:

 

$string="1,2,3,4,5,6,7,8,9,89,87,83";

 

Then I want to remove ID 8. So I do this:

 

$string=str_replace(",8","",$string);

 

Simple enough right? BUT it's going to remove the ,8 from ID's 89 and 87 also! And if it's at the beginning or end of the string I think that could pose another problem as well..

$string=str_replace(",8,", ",", $string);

 

Should do the trick.

 

Ah I forgot to give that example, yeah that's was one of the solutions I thought of, but if the ID is at the beginning or end then it's not going to work:

 

$string="1,2,3,4,5,6,7,8";

 

I seem to run into this type of string replace problem quite often, surely there's got to be some PHP function I don't know about that deals with exactly this.

Found a solution, although I'm sure there's a regex that could do this in one line :(

 

$string = ",8,1,2,3,4,5,6,7,8,9,89,87,83,8";

$patterns = array();

$patterns[0] = '/(,8,)/';

$patterns[1] = '/(,8)$/';

$replacements = array();

$replacements[1] = ',';

$replacements[0] = '';

echo preg_replace($patterns, $replacements, $string);

 

Here's a solution using a function:

<?php
function remove_value($str,$val) {
$ary = explode(',',$str);
$keys = array_keys($ary,$val);
if ($keys !== false) {
	foreach ($keys as $k) {
		unset($ary[$k]);
	}
}
return (implode(',',$ary));
}
$str = ",8,1,2,3,4,5,6,7,8,9,89,87,83,8";
echo remove_value($str,'8');
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.