Mr world wide
Mr world wide

Reputation: 4814

How to reverse a string and replace chars?

I have been asked by an interviewer for a test:

$string = "This is sample string";
// Output: "string_sample_is_This";

what does this question mean..?

I assumed that he was asking about a simple echo, am I right or would he expected something else from me ?

<?php       
    $string = "This is sample string";
    echo $string;
?>

Upvotes: 1

Views: 96

Answers (3)

pirs
pirs

Reputation: 2463

He definetly asked for something else ...

<?php 

    $string = explode(" ","This is sample string");
    $string = array_reverse($string);
    $string = implode("_",$string);
    echo $string;

?>

More :

PHP explode()

PHP array_reverse()

PHP implode()

Upvotes: 4

Nandhi Kumar
Nandhi Kumar

Reputation: 353

No he told to reverse the sentence and echo the string.

<?php
    $string = "This is sample string";
    $string1 = '';
    $string_array = explode(' ',$string);
    $count = count($string_array) - 1;
    for($i=$count; $i>=0; $i--)
    {
    if($i == 0)
    {
    $string1 .= $string_array[$i];
    }
    else
    {
    $string1 .= $string_array[$i]."_";
    }
    }
    echo $string1;
?>

Upvotes: 2

CoderLee
CoderLee

Reputation: 3479

That looks more like you are being asked to reverse the order of the tokens in the string and replace the delimiter from single spaces to the _ character. I would assume that or something similar to such was being asked.

Upvotes: 2

Related Questions