>  기사  >  백엔드 개발  >  PHP의 역방향 문자열

PHP의 역방향 문자열

PHPz
PHPz원래의
2024-08-29 13:12:35322검색

이 글에서는 PHP의 Reverse String에 대해 알아 보겠습니다. 문자열은 뒷면에서 호출되는 문자 모음입니다. 이러한 문자 모음은 PHP 함수 strrev()를 반전시키거나 간단한 PHP 프로그래밍 코드를 사용하여 사용할 수 있습니다. 예를 들어 PAVANKUMAR를 반전하면 RAMUKNAVAP이 됩니다

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

논리:

  • 처음에는 문자열을 변수에 할당합니다.
  • 이제 문자열 길이를 계산해 보세요.
  • 이제 반전된 문자열을 저장하기 위해 새 변수를 만듭니다.
  • 그런 다음 for 루프, while 루프, while 루프 등과 같은 루프를 진행합니다.
  • 루프 내부에서 문자열을 연결합니다.
  • 그런 다음 중간에 생성된 새 변수에 저장된 반전된 문자열을 표시/인쇄합니다.

다양한 루프를 사용하는 PHP의 문자열 역방향

PHP 프로그래밍 언어에서 문자열을 뒤집기 위해 FOR LOOP, WHILE LOOP, DO WHILE LOOP, RECURSIVE METHOD 등과 같은 다양한 루프를 사용합니다.

 1. strrev() 함수 사용

  • 아래 예제/구문은 문자열을 반전시키기 위해 이미 사전 정의된 함수 strrev()를 사용하여 원래 문자열을 반전합니다. 예제에서는 문자열을 저장하기 위해 $string1 변수가 생성됩니다. 즉, 원래 문자열을 의미합니다. 그런 다음 strtev() 함수의 도움으로 원래 문자열과 반전된 문자열을 인쇄하기 위해 echo 문을 사용하고 다음으로 인쇄합니다. 둘 다 연결합니다.
  • 아래 프로그램의 출력을 보면 문자열이 반전되었는지 확인할 수 있습니다.

코드:

<?php
$string1 = "PAVANKUMAR";
echo "Reversed string of the $string1 is " .strrev ( $string1 );
?>

출력:

PHP의 역방향 문자열

2. For 루프 사용

  • 아래 예에서는 string1 변수의 값을 "PAVANSAKE"로 할당하여 "$string1" 변수를 생성합니다. 그런 다음 strlen() 함수를 사용하여 $string1 변수의 길이를 저장하기 위해 $length 변수를 생성합니다. 이제 for 루프는 "$length1-1", "$i1>=0", "$i1 – -"과 같은 초기화, 조건 및 증분 값과 함께 사용됩니다. 그런 다음 $string1 변수의 인덱스 값은 $i1의 초기화를 $length-1과 동일하게 사용하여 뒷면에서 호출됩니다.
  • 처음에는 FOR LOOP가 “원래 문자열 – 1” 값의 길이 값으로 시작됩니다. 그런 다음 "i1>=0" 조건을 확인하여 루프가 실행되기 시작하고 원래 문자열의 인덱스가 역방향으로 호출됩니다. 마찬가지로 루프는 조건이 FALSE가 될 때까지 각 반복마다 뒤에서 각 인덱스 값을 인쇄합니다. 마지막으로 FOR 루프를 사용하여 문자열의 역순을 얻습니다.

코드:

<?php
$string1 = "PAVANSAKE";
$length1 = strlen($string1);
for ($i1=($length1-1) ; $i1 >= 0 ; $i1--)
{
echo $string1[$i1];
}
?>

출력:

PHP의 역방향 문자열

3. While 루프 사용

  • 아래 예제에서는 원래 문자열 "PAVANSAKEkumar"를 사용하여 반전된 문자열을 인쇄하기 위해 루프를 사용했습니다.
  • 아래 구문/php 프로그램에서는 처음에 $string1 변수에 "PAVANSAKEkumar" 문자열 값이 할당된 다음 $string1 변수 값의 길이를 계산하여 $length1 변수에 저장됩니다. 항상 정수입니다. 이제 $i1 변수는 문자열 변수 값의 길이 -1($length1-1)입니다.
  • 이제 여기에서 "$i1>=0" 조건을 사용하여 WHILE 루프를 시작한 다음 $i1 값이 원래 문자열의 인덱스 값 중 마지막 값이므로 문자열의 인덱스 값을 뒤에서 인쇄합니다. . 이후에는 원래 문자열을 반전시키기 위해 감소 작업이 수행됩니다($i1=$i1-1).

코드:

<?php
$string1 = "PAVANSAKEkumar";
$length1 = strlen($string1);
$i1=$length1-1;
while($i1>=0){
echo $string1[$i1];
$i1=$i1-1;
}
?>

출력:

PHP의 역방향 문자열

4. do while 루프 사용

  • DO while 루프를 사용하여 PHP에서 문자열을 반전시키는 프로그램은 다음과 같습니다. 아래 예에서는 WHILE LOOP와 같습니다. 모든 논리 용어는 WHILE LOOP와 동일하지만 약간 다릅니다. 처음에 조건을 확인하지 않고 먼저 출력을 인쇄합니다.
  • 따라서 조건 결과가 FALSE인 경우에도 출력을 인쇄하는 경우에도 마찬가지입니다.

코드:

<?php
$string1 = "PAVANSAKEkumaran";
$length1 = strlen($string1);
$i1=$length1-1;
do{
echo $string1[$i1];
$i1=$i1-1;
}
while($i1>=0)
?>

출력:

PHP의 역방향 문자열

5. Using the Recursion Technique and the substr()

  • Here in the below example reversing the string is done using the recursion technique and the substr() function. Substr() function will help in getting the original string’s substring. Here a new function called Reverse() also defined which is passed as an argument with the string.
  • At each and every recursive call, substr() method is used in order to extract the argument’s string of the first character and it is called as Reverse () function again just bypassing the argument’s remaining part and then the first character concatenated at the string’s end from the current call. Check the below to know more.
  • The reverse () function is created to reverse a string using some code in it with the recursion technique. $len1 is created to store the length of the string specified. Then if the length of the variable equals to 1 i.e. one letter then it will return the same.
  • If the string is not one letter then the else condition works by calling the letters from behind one by one using “length – -“ and also calling the function back in order to make a recursive loop using the function (calling the function in function using the library function of PHP). $str1 variable is storing the original string as a variable. Now printing the function result which is the reverse of the string.

Code:

<?php
function Reverse($str1){
$len1 = strlen($str1);
if($len1 == 1){
return $str1;
}
else{
$len1--;
return Reverse(substr($str1,1, $len1))
. substr($str1, 0, 1);
}
}
$str1 = "PavanKumarSake";
print_r(Reverse($str1));
?>

Output:

PHP의 역방향 문자열

6. Reversing String without using any library functions of PHP

  • The below syntax/ program example is done by swapping the index’s characters using the for loop like first character’s index is replaced by the last character’s index then the second character is replaced by the second from the last and so on until we reach the middle index of the string.
  • The below example is done without using any of the library functions. Here in the below example, $i2 variable is assigned with the length of the original string-1 and $j2 value is stored with value as “0” then in the loop will continue by swapping the indexes by checking the condition “$j2

Code:


Output:

PHP의 역방향 문자열

Conclusion

I hope you understood the concept of logic of reversing the input string and how to reverse a string using various techniques using an example for each one with an explanation.

위 내용은 PHP의 역방향 문자열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP의 팩토리얼다음 기사:PHP의 팩토리얼