Question

J'ai une chaîne.

Je veux inverser les lettres dans chaque mot pas inverser l'ordre des mots.

comme - 'ma chaîne'

doit être

'YM gnirts'

Était-ce utile?

La solution

Cela devrait fonctionner:

$words = explode(' ', $string);
$words = array_map('strrev', $words);
echo implode(' ', $words);

Ou comme une doublure:

echo implode(' ', array_map('strrev', explode(' ', $string)));

Autres conseils

echo implode(' ', array_reverse(explode(' ', strrev('my string'))));

Ceci est considérablement plus rapide que d'inverser chaque chaîne du tableau après avoir fait exploser la chaîne d'origine.

Functionified:

<?php

function flipit($string){
    return implode(' ',array_map('strrev',explode(' ',$string)));
}

echo flipit('my string'); //ym gnirts

?>

Cela devrait faire l'affaire:

function reverse_words($input) {
    $rev_words = [];
    $words = split(" ", $input);
    foreach($words as $word) {
        $rev_words[] = strrev($word);
    }
    return join(" ", $rev_words);
}

Je ferais:

$string = "my string";
$reverse_string = "";

// Get each word
$words = explode(' ', $string);
foreach($words as $word)
{
  // Reverse the word, add a space
  $reverse_string .= strrev($word) . ' ';
}

// remove the last inserted space
$reverse_string = substr($reverse_string, 0, strlen($reverse_string) - 1);
echo $reverse_string;
// result: ym gnirts
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top