php reverse string method

angryTom
Release: 2023-04-07 09:18:01
Original
3734 people have browsed it

php reverse string method

During the interview for PHP-related jobs, we are likely to encounter this problem, how to reverse a string. Below we will answer this question for you.

Recommended tutorial: PHP video tutorial

##Method 1

Use the strrev() function to reverse a string.

Grammar strrev(string)

Example

<?php 
echo strrev("Hello World!"); 
?>
Copy after login

Output: !dlroW olleH

Method 2

Split the string into an array, and then traverse and splice it, as follows

function revstr($str)
{
	if (strlen($str) <= 1) return $str;
 
	$newstr  = &#39;&#39;;
	$str2arr = str_split($str,1);
	foreach ($str2arr as $word) {
		$newstr = $word.$newstr;
	}
 
	return $newstr;
}
Copy after login

Method 3## Use recursion, the code is as follows

function revstr($str)
{
	if (strlen($str) <= 1) return $str;
 
	$newstr = &#39;&#39;;
	$newstr .= substr($str,-1).revstr(substr($str,0,strlen($str)-1));
 
	return $newstr;
}
Copy after login

ps: This method should be what the interviewer wants to see Answer.

The above is the detailed content of php reverse string method. 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