Sling Academy
Home/PHP/How to reverse a string in PHP

How to reverse a string in PHP

Last updated: January 10, 2024

Introduction

Reversing a string, a common task in programming, can be implemented in multiple ways in PHP. This tutorial walks you through several methods to invert a string, from the simple built-in function to advanced techniques.

Using strrev()

The simplest approach to reverse a string in PHP is by using the strrev() function. It’s a built-in function provided by PHP to reverse strings.

<?php
$str = "Hello, World!";
$reversed = strrev($str);
echo $reversed; // Outputs: !dlroW ,olleH
?>

This method is straightforward and recommended for most cases.

Manual Loop Method

If for educational purposes or for customization, you want to reverse a string manually, you can use a loop.

<?php
$str = "Hello, World!";
$reversed = "";
for ($i = strlen($str) - 1; $i >= 0; $i--) {
    $reversed .= $str[$i];
}
echo $reversed; // Outputs: !dlroW ,olleH
?>

This gives you more control over the process, which can be useful in certain scenarios.

Using array functions

PHP’s array functions can also be utilized to reverse a string by splitting the string into an array, reversing the array, and then joining it back into a string.

<?php
$str = "Hello, World!";
$reversed = implode('', array_reverse(str_split($str)));
echo $reversed; // Outputs: !dlroW ,olleH
?>

This method is useful for reversing strings that are based on multibyte characters, like UTF-8.

Regular Expression and Reversing

For even more advanced manipulation, PHP’s preg_match() and preg_replace() functions can be used to reverse string patterns within larger strings. Here’s how to reverse each word in a string individually:

<?php
$str = "Hello, World!";
echo preg_replace_callback('/\b(\w+)(\W+)/', function($matches) {
    return strrev($matches[1]) . $matches[2];
}, $str);
// Outputs: olleH, !dlroW
?>

This method is powerful for pattern-specific string manipulation and can accomplish complex tasks beyond simple reversal.

Benchmarking Performance

When choosing the right method for reversing strings in PHP, it may be beneficial to consider the performance, especially if you are working with very large strings or a high amount of operations. Profiling functions like microtime() can be used to benchmark these methods.

<?php
// Example use of microtime() for benchmarking
$start = microtime(true);
// Call your string reverse function/method here
$time_elapsed = microtime(true) - $start;
echo "Time elapsed: " . $time_elapsed . " sec";
?>

Conclusion

In conclusion, PHP offers several ways to reverse a string, each with its own use cases and benefits. From the simple use of strrev() to the more complex pattern matching with regular expressions, PHP provides the tools for developers to manage and manipulate strings efficiently.

Next Article: PHP: How to convert a string to char codes and vice versa

Previous Article: Process escape sequences in a string in PHP

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array