Home  >  Article  >  Backend Development  >  How to reverse string by word in php

How to reverse string by word in php

青灯夜游
青灯夜游Original
2021-11-09 17:52:201846browse

Reversal method: 1. Use the "explode(' ',$str)" statement to convert the string into an array; 2. Use the "array_reverse($arr)" statement to reverse the array and use the opposite element Return the array in sequence; 3. Use the "implode(' ',$arr)" statement to convert the reversed array into a string.

How to reverse string by word in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php will string Reverse by words

Implementation method: Then array

  • First convert the string into array elements by words

  • Then use array_reverse() to reverse the array

  • Then convert the reversed array into a string

implementation Code:

<?php
$str = "Reversing a string by word";
// break the string up into words
$arr = explode(&#39; &#39;,$str );
// reverse the array of words
$arr = array_reverse($arr);
// rebuild the string
$str = implode(&#39; &#39;,$arr);
print $str;
?>

Output result:

How to reverse string by word in php

Explanation:

  • explode() function can be based on The string delimiter splits the string, that is, it splits a string into several substrings based on the delimiter, and then combines these substrings into an array and returns it.

  • array_reverse() function returns an array in reverse element order.

  • implode() function can convert a one-dimensional array into a string

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to reverse string by word in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does for mean in phpNext article:What does for mean in php