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'.

3 Answers 3

4

This can be your solution:

$str = 'this,is,the,first,string';
$str = str_replace(',', ', ', $str);
echo preg_replace('/(.*),/', '$1 and', $str);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.