Below is my Code to Reverse a String..
The code runs well but I need to wrap this code inside Paramaterized function
in which user pass a string inside function and get return output.
<?php
$string = trim("This");
$len =strlen($string);
$stringExp = str_split($string);
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
?>
for Ex -
I want above string reversal code logic like below function...
<?php
$str = "rahul";
echo reverse($str);
function reverse($str)
{
for ($i = 0, $j = strlen($str) - 1; $i < $j; $i++, $j--) {
$tmp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $tmp;
}
return $str;
}
?>
Simply try this
$str = "rahul";
echo reverse($str);
function reverse($str)
{
$tmp = '';
for($i = (strlen($str)-1);$i >= 0; $i--) {
$tmp .= $str[$i];
}
return $tmp;
}
There is strev() function which does it but if you need write your own here is the code
$str = "abcde";
function reverse ($str)
{
$output = '';
for ($i = strlen($str)-1; $i >= 0 ; --$i) {
$output .= $str[$i];
}
return $output;
}
echo reverse($str);
Related
How can I shuffle the php string?
I want to show all of the string in the shuffled output.
example input : abc
output :
abc
acb
bac
bca
cab
cba
my code :
function permutations() {
global $running;
global $characters;
global $bitmask;
if (count($running) == count($characters)) {
printf("%s\n", implode($running));
} else {
for ($i=0; $i<count($characters); $i++) {
if ( (($bitmask>>$i)&1) == 0 ) {
array_push($running, $characters[$i]);
$bitmask |= (1<<$i);
permutations();
array_pop($running);
}
}
}
}
fscanf(STDIN, '%s', $raw_input);
$characters = str_split($raw_input);
$running = array();
$bitmask = 0;
permutations();
always get error for the fscanf()
This is sample function for shuffling any characters. You can use only shuffle_string function for your purpose.
// direct function for shuffling characters of any string
function shuffle_string ($string) {
$string_len = strlen($string);
permute($string, 0, $string_len);
}
// to generate and echo all N! permutations of $string.
function permute($string, $i, $n) {
if ($i == $n) {
echo "$string\n";
} else {
for ($j = $i; $j < $n; $j++) {
swap($string, $i, $j);
permute($string, $i+1, $n);
swap($string, $i, $j); // backtracking.
}
}
}
// to swap the character at position $i and $j of $string.
function swap(&$string, $i, $j) {
$temp = $string[$i];
$string[$i] = $string[$j];
$string[$j] = $temp;
}
shuffle_string('Hey');
Hope this will help:
<?php
function permutations($set)
{
$solutions=array();
$n=count($set);
$p=array_keys($set);
$i=1;
while ($i<$n)
{
if ($p[$i]>0)
{
$p[$i]--;
$j=0;
if ($i%2==1)
$j=$p[$i];
//swap
$tmp=$set[$j];
$set[$j]=$set[$i];
$set[$i]=$tmp;
$i=1;
$solutions[]=$set;
}
elseif ($p[$i]==0)
{
$p[$i]=$i;
$i++;
}
}
return $solutions;
}
$string = 'abc';
$string = str_split($string);
$all_per = permutations($string);
foreach($all_per as $key => $value){
$str[]= implode(',',$value);
}
print_r($str);
<?php
echo my_string_replace("world","jonathan","hello world helloworld");
function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"
error_reporting(0); used for hide "Uninitialized string offset" notice.
<?php
function str_v2($num){
error_reporting(0);
for($i=0; $num[$i] != "";$i++);
echo $i; }//end of function
$name = "Hope this will work.";
echo str_v2($name);
?>
That was a fun brain teaser. Here you go:
echo my_string_replace("world", "jonathan", "hello world helloworld");
function my_string_replace($find, $replace, $string)
{
$characterCount = strlen($string);
$findCount = strlen($find);
$replaceCount = strlen($replace);
for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
if ($string[$i] == $find[0]) {
$j = 1;
$found = true;
while ($j < $findCount) {
if ($string[$i + $j] != $find[$j]) {
$found = false;
break;
}
$j++;
}
if ($found) {
// copy string until current position
$replaced = '';
for ($x = 0; $x < $i; $x++) {
$replaced .= $string[$x];
}
// append replacement
$replaced .= $replace;
// copy after match till end
for ($x = $i + $findCount; $x < $characterCount; $x++) {
$replaced .= $string[$x];
}
// continue with replaced string, after replacement
$string = $replaced;
$characterCount = strlen($string);
$i = $i + $replaceCount;
}
}
}
return $string;
}
In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().
Uninitialized string offset: -1 in
D:\xampp\htdocs\PhpProject1\index.php on line xx
$string = "ZEESHAN";
$i =0;
while(($string[$i])!=null){
$i++;
}
$i--;
while(($string[$i])!=null){
echo $string[$i];
$i--;
}
$string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
echo $reverse;
Try -
$string = "ZEESHAN";
$j = 0;
while(!empty($string[$j])) {
$j++;
}
for($i = ($j-1); $i >= 0; $i--) {
echo $string[$i];
}
Output
NAHSEEZ
I have created a simple logic for string reversal
$str = 'ABCD';
$strReversed = '';
$length = strlen($str);
for($i=$length-1; $i >= 0; $i--){
$strReversed .= $str[$i];
}
echo $strReversed;
You can use while and for loop like as
$string = "ZEESHAN";
$reverse = "";
$j = 0;
while(isset($string[$j])){
$j++;
}
for($i = $j - 1; $i >= 0; $i--){
$reverse .= $string[$i];
}
echo $reverse;
You can try it with count_chars and array_sum
<?php
$string = "ZEESHAN";
$count=array_sum(count_chars($string));
for($i=$count -1 ;$i>=0;$i--){
echo $string[$i];
}
?>
If you dont want any php string function you can try this way with krsort and array:
<?php
$string = "ZEESHAN";
$arr = array();
$i=0;
while(isset($string[$i])){
$arr[$i] = $string[$i];
$i++;
}
krsort($arr);
$final = implode("",$arr);
var_dump($final);
?>
//Program for reversing a string
<?php
class str_rev{
public function Revese_Str($string){
$reverse = '';
$i=0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
return $reverse;
}
}
$object = new str_rev();
echo $object->Revese_Str('Ayush Jain');
Check this code to resolve this problem.
<?php
$string = "ZEESHAN";
$i =0;
while(!empty($string[$i])){
$i++;
}
$i--;
while(!empty($string[$i])){
echo $string[$i];
$i--;
}
?>
You can do this
$string = "heya";
$i = strlen("heya") - 1;
$newStr = "";
while($i >= 0) {
$newStr .= $string[$i];
$i--;
}
echo $newStr; // output: ayeh
<!doctype html>
<html>
<body>
<center>
<form action="#" method="get">
<br>
<input type="text" name="txt"/>
<br><br>
<input type="submit" name="submit"/>
<br><br>
</form>
<?php
if(isset($_GET["submit"])) {
$name = $_GET["txt"];
for ($i = 0; isset($name[$i]); $i++) {
$j = $i;
}
for ($k = $j; isset($name[$k]); $k--) {
echo $name[$k];
}
}
Please take a look the below code: Reverse the string
$str = 'abcdefg';
$reverseString = '';
for($i=strlen($str);$i<=strlen($str);$i--){
$reverseString .= $str[$i];
if($i==0)
break;
}
echo $reverseString;
The above code output is:
gfedcba
<?php
$string = 'ZEESHAN';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
echo $reverse;
?>
Check complete post: https://www.troposal.com/reverse-string-without-function-php/
I was challenged by a friend to code some PHP to find the longest palindrome in provided text, my solution is below, how could I make it more efficient?
$string = file_get_contents("http://challenge.greplin.com/static/gettysburg.txt");
echo $string;
function isPalendrone($string) {
if ($string == strrev($string))
return true;
else
return false;
}
$longest = "";
for($i = 0; $i < strlen($string)-1; $i++) {
$afterCurrent = substr($string, $i);
for($j = 0; $j < strlen($afterCurrent)-1; $j++) {
$section = substr($afterCurrent, 0, $j);
if(isPalendrone($section)) {
if(strlen($longest)<strlen($section)) {
$longest = $section;
}
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";
This reverses the entire string and just does substr() matches against each:
$rev = strrev($txt);
$len = strlen($txt);
$longest_len = 0;
$longest_str = null;
for ($i = 0; $i < $len; ++$i)
{
for ($j = $len - $i; $j > $longest_len; --$j)
{
if (substr($txt, $i, $j) == substr($rev, $len-$i-$j, $j))
{
$longest_len = $j;
$longest_str = substr($txt, $i, $j);
break;
}
}
}
I didn't try to optimize the implementation. e.g., It might be a little faster to skip the substr and do a char-by-char approach, because you could break out faster. In that case, you wouldn't really even need to reverse the string.
To get the longest palindrome - you have to start with longest string (not with shortest like you do now), check it and break on first match.
Also you'd better just keep 2 pointers ($i and $j) and not perform substr twice. It is enough to have i and j and substr once, right before you perform if(isPalendrone()) condition.
My implementation (~20% faster than yours):
<?php
$string = 'FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth';
function isPalendrone($string) {
return $string == strrev($string);
}
$longest = '';
$length = strlen($string);
for ($i = 0; $i < $length - 1; $i++) {
for ($j = $length - $i; $j > 1; $j--) {
if (isPalendrone(substr($string, $i, $j))) {
$new = substr($string, $i, $j);
if (strlen($new) > strlen($longest)) $longest = $new;
break;
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";
I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.