2

I have a string in a DB table which is separated by a comma i.e. this,is,the,first,sting

What I would like to do and don't know how is to have the string outputted like: this, is, the, first and string

Note the spaces and the last comma is replaced by the word 'and'.

puks1978
  • 3,667
  • 11
  • 44
  • 103

3 Answers3

4

This can be your solution:

$str = 'this,is,the,first,string';
$str = str_replace(',', ', ', $str);
echo preg_replace('/(.*),/', '$1 and', $str);
mauris
  • 42,982
  • 15
  • 99
  • 131
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

First use, the function provided in this answer: PHP Replace last occurrence of a String in a String?

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos === false)
    {
        return $subject;
    }
    else
    {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
}

Then, you should perform a common str_replace on text to replace all other commas:

$string = str_lreplace(',', 'and ', $string);
str_replace(',',', ',$string);
Community
  • 1
  • 1
sallaigy
  • 1,524
  • 1
  • 13
  • 12
0
$words = explode( ',', $string );
$output_string = '';
for( $x = 0; $x < count($words); x++ ){
    if( $x == 0 ){
        $output = $words[$x];
    }else if( $x == (count($words) - 1) ){
        $output .= ', and ' . $words[$x]; 
    }else{
        $output .= ', ' . $words[$x];
    }
}
Homer6
  • 15,034
  • 11
  • 61
  • 81