Forum Moderators: coopster

Message Too Old, No Replies

Replace last occurence

         

ntbgl

1:50 am on Feb 20, 2009 (gmt 0)

10+ Year Member



I have a string like this:

$list="I would like to buy some apples, bannanas, pears, grapes."

What I would like to do is to take this string and replace the last occurance of "," with " and", to make the string look like this:

$list="I would like to buy some apples, bannanas, pears and grapes."

tbarbedo

2:38 am on Feb 20, 2009 (gmt 0)

10+ Year Member



here's a way to look at it...

split the every character in the string into an array.
count up how many ',' array values there are
find the position of the last ',' value and replace with " and"
then merge all the array values back into a string

cameraman

5:55 am on Feb 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could use a regular expression:
$newlist = preg_replace('#,(?![^,]+,)#',' and',$list);

The regular expression looks for a comma and uses a negative lookahead assertion to look for non-commas followed by a comma. Google "regex lookahead" for a more comprehensive explanation.

VarX

6:03 am on Feb 20, 2009 (gmt 0)

10+ Year Member



check this out is this what you need

<?php
$list="I would like to buy some apples, bannanas, pears, grapes." ;
#check the last occurence and replace the value;
$last=strripos($list,',');
$list_explode=str_split($list);
for ($i = 0; $i<=count($list_explode); $i++){
if ($i == $last){
$list_explode[$i] =' and';
}

}
$sorted = implode($list_explode,'');
echo $sorted;
?>

#echos I would like to buy some apples, bannanas, pears and grapes.

[edited by: VarX at 6:07 am (utc) on Feb. 20, 2009]

dreamcatcher

8:53 am on Feb 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Something like this would also probably work:

$list="I would like to buy some apples, bannanas, pears, grapes.";
echo substr($list,0,strrpos($list,',')).' and '.substr(strrchr($list, ','), 1);

dc

whoisgregg

2:40 pm on Feb 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or something like this:

$list="I would like to buy some apples, bannanas, pears, grapes."; 
$result = strrev(implode(strrev(" and"), explode(",", strrev($list), 2)));

:)