How to reverse string by word in php

青灯夜游
Release: 2023-03-13 19:04:01
Original
1837 people have browsed it

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;
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template