
|
View Full Version : Another Quickie - Editing a String
Jeanco 05-11-2005, 11:46 AM Ok a quickie. I have a string of emails in the format:
email1@email.com,me@me.com,sdf@kdsf.com,you@you.net,
(note there is a trailing comma). Anyway, if this is stored in a string, say $email... what would I use to delete one of the email addresses from the middle, say me@me.com. So the final string would be:
email1@email.com,sdf@kdsf.com,you@you.net,
Thanks.
laserlight 05-11-2005, 12:23 PM One way is to create an array (or some similiar construct) of email addresses from the string of email addresses.
Search this array for the email address, and remove (or otherwise note) it.
Then re-construct the string from the modified array.
Another way is to search for the position of the email address in the string.
Once you know the start and end point, you just copy everything else into a new string.
intransit 05-11-2005, 02:30 PM Try:
$list=explode(",",$email);
$j=0;
for($i=0;$i<count($list)-1;$i++){
if($list[$i]!=$needle){$newlist[$j]=$list[$i];$j++;}
}
$email=implode(",",$newlist);
Jeanco 05-11-2005, 02:36 PM perfect. I'll give it a try. Thx
Jeanco 05-11-2005, 03:04 PM Worked like a charm.
fusionrays 05-11-2005, 04:14 PM Just an alternative:
$email_string = 'email1@email.com,me@me.com,sdf@kdsf.com,you@you.net,';
$email_replace = 'me@me.com';
$email_string = preg_replace ("/$email_replace,/", '', $email_string);
print $email_string;
laserlight 05-13-2005, 02:45 AM Actually, an improvement to intransit's code would be:
$haystack = explode(",", $email);
if (($key = array_search($needle, $haystack)) !== false) {
unset($haystack[$key]);
$email = implode(",", $haystack);
}
This is basically:
One way is to create an array (or some similiar construct) of email addresses from the string of email addresses.
Search this array for the email address, and remove (or otherwise note) it.
Then re-construct the string from the modified array.
intransit's method takes the unnecessary step of creating a new array first, and then re-constructing the string from the new array.
BurstChris 05-13-2005, 07:57 AM it is a string, use string replacement or regex functions.
creating an array and looping thru it seems like an overkill, imo.
laserlight 05-13-2005, 10:32 AM Well, the CSV-like format of the string makes it easy to work with explode/implode.
There could be a gotcha in using the 2nd method with str_replace() (preg_replace() would also be overkill in this case) if for some reason the last item did not have a trailing comma as stipulated by Jeanco.
Jeanco 05-13-2005, 10:41 AM thanks for the informative thread guys. Very interesting.
|