Home  >  Article  >  Backend Development  >  PHP algorithm exercise three: swap the first and last characters in the string

PHP algorithm exercise three: swap the first and last characters in the string

藏色散人
藏色散人Original
2021-08-05 10:26:573186browse

In the previous article "PHP Algorithm Exercise 2: Finding the Absolute Difference between n and the Specified Number", we introduced how to find the absolute difference between two numbers and three times the difference. Today Continuing the PHP basic algorithm series, but it is not a simple calculation between values. Let’s look down for details~

The theme of this article’s exercise is “Write a PHP program to exchange the first sum in a given string. last character and return the new string".

Based on this question, let’s practice it yourself~

I will give you my implementation method below:

The PHP code is as follows:

<?php

function test($str)
{
    return strlen($str) > 1 ? substr($str, strlen($str) - 1).substr($str, 1, strlen($str) - 2). substr($str, 0, 1) : $str;

}

echo test("abcd")."<br>";
echo test("a")."<br>";
echo test("xy")."<br>";

The output result is:

PHP algorithm exercise three: swap the first and last characters in the string

In this example, the first string we give is "abcd", then exchange the first and last string characters, and the new string output is "dbca";

The second string given is "a", and the output is a;

The third string is "xy" , the new string output is "yx".

The ternary operator "?:", as well as the strlen and substr functions are used here.

The following is a brief introduction to the functions of the two functions:

The function of strlen() is to return the length of the string. The syntax is "strlen(string)"; its return The value is the length of the string returned if successful, or 0 if the string is empty.

Note: Before PHP 5.3.0, this function treated the array as a string Array, thus returning a string of length 5 and generating an E_NOTICE level error.

The function of substr() is to return part of the string. The syntax is "substr(string,start,length)"; its return value is the extracted part of the returned string. If Returns FALSE on failure, or an empty string.

Note: If the start parameter is a negative number and length is less than or equal to start, length is 0.

Finally, I would like to recommend "PHP Video Tutorial" to everyone~ Come and learn!

The above is the detailed content of PHP algorithm exercise three: swap the first and last characters in the string. 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