Home  >  Article  >  Backend Development  >  php reverse string method

php reverse string method

angryTom
angryTomOriginal
2019-08-22 16:23:513718browse

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!"); 
?>

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;
}

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;
}

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!

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:How to use php returnNext article:How to use php return