PHP: Reverse the Chars & Nums While Retain Special Chars

Follow by Email
Facebook
Google+
http://xtremepassion.leladystore.com/2018/12/php-reverse-the-chars-nums-while-retain-special-chars/
YouTube
PINTEREST
INSTAGRAM


Given a string, that contains special character together with alphabets and numbers (‘a’ to ‘z’, ‘A’ to ‘Z’, and ‘0’ to ‘9’), reverse the alphabets and numbers in a way that special characters remains unchange from it’s current position.
Examples:
input: s%b#@cd
output: d%c#@bs
input: 1.30^AD&fj{00*x]
output: x.00^jf&DA{03*1]

Below is how you code with PHP:

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
<?php
/**
 *=-----------------------------------------------------------=
 * Original: bctest.php
 *=-----------------------------------------------------------=
 * Author: LJLEE:  10-12-2018
 * Modified on: 10 Dec 2018
 *
 */

// Define variables
$j = 0;
$k = 0;
$pattern = "/[a-z0-9]/i"; //range from a to z, 0 to 9 without case sensitive


if (empty($_POST["valStr"])) {
    $str = "";
} else {
    $str = $_POST["valStr"];
}

//Store the character string
//Store the nonChar String
For ($i=strlen($str)-1; $i >=0; $i--){ 
	
	if(preg_match($pattern, $str[$i])){//Get reversal chars and nums
	    $newStr[$j] = $str[$i];
	    $j++;
	    
	}else{//Get special chars at its current position 
	    $newStr2[$i] = $str[$i];
	}
}

//store the result
For ($i=0; $i<strlen($str); $i++){
	
	if(empty($newStr2[$i])){
	    $result[$i] = $newStr[$k++];
	}else{
	    $result[$i] = $newStr2[$i];
	}
}

?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="w3-container">
    <div class="w3-panel w3-sand w3-leftbar">
    <p><i class="fa fa-quote-right w3-xlarge w3-opacity"></i><br>
    <i class="w3-serif w3-large">
        Given a string, that contains special character together with alphabets and numbers (‘a’ to ‘z’, ‘A’ to ‘Z’, and '0' to '9'), reverse the alphabets and numbers in a way that special characters remains unchange from it's current position. <br />
        Examples: <br />
        input: s%b#@cd <br />
        output: d%c#@bs <br />
        input: 1.30^AD&fj{00*x] <br />
        output: x.00^jf&DA{03*1]
        </i></p>
  </div>
    <p>
        Value to Reverse: <input type="text" name="valStr" value="<?php echo $str;?>">
    </p>
    <p>
        <input type="submit" name="submit" value="Submit">
    </p>
</form>
<?php
//Display the result
if(count($result)!= 0){
    
    echo "Result: ";
    
    for($s=0; $s<strlen($str); $s++){
        echo $result[$s];
    }
}else{
    echo "Please input string to test";
}

?>
</body>
</html>

Run the test HERE: bctest.php

Leave a Reply

Your email address will not be published. Required fields are marked *

220 views