Inversion methods: 1. use "explode(' ',$str)" statement to convert string to array; 2. use "array_reverse($arr)" statement to invert the array and return the array in the reverse order of elements; 3. use "implode(' ',$arr)" statement to convert the inverse array to string.

php to invert strings by word

Implementation method:

  • First convert the string into an array of elements by word

  • Then use array_reverse() to invert the array

  • Then convert the inverse array to a string

Implementation code:

1

2

3

4

5

6

7

8

9

10

<?php

$str = "Reversing a string by word";

// break the string up into words

$arr = explode(' ',$str );

// reverse the array of words

$arr = array_reverse($arr);

// rebuild the string

$str = implode(' ',$arr);

print $str;

?>

Output results:

  • The explode() function splits a string based on the string separator, i.e. it splits a string into several substrings based on the separator, and then combines these substrings into an array and returns it.

  • The array_reverse() function returns an array in the reverse order of its elements.

  • The implode() function converts a one-dimensional array into a string

keywords: php