How add to a backspace character to a string literal? - php

I use \b to generate backspace in PHP: But I think it doesn't work:
if(isset($_GET['submit'])){
$n = $_GET['n'];
$c = $_GET['c'];
$space = " "; $i=0; $j=0; $k=0;
do{
$space = $space." ";
$i++;
}while($i < $n);
for($j=0; $j < $n ; $j++){
echo $space;
for($k=0; $k < $j*2 - 1; $k++){
echo $c;
}
echo $space."\b";
echo "<br />";
}
}

If you want to delete last char in a string just do:
$space = substr($space,0,-1); //> Reccomanded
or
substr($space,0,count($space)-1); //> Slower
or
substr_replace($space,'',-1); //> Uglier

Maybe you mean this: "\x8" ?

Indeed, it's not on the list. You have to use the octal or hexadecimal notation.
In any case, the backspace character has little use outside a text console, not to mention HTML.

Related

Using PHP how I can print a string reverse

I want to print the string reversed. I found this code but I can't understand what is the meaning of immediate two line after the for loop.
<?php
$s = 'abcdefg';
$j = 0;
for ($i = strlen($s) - 1; $i >= 0; $i--) {
$s .= $s[$i];
$s[$i] = NULL;
$j++;
}
echo "$s";
echo "<br/>";
echo "there are " . $j . " character in the string.";
?>
Just simply use strrev
<?php
echo strrev("abcdefg");
$s .= $s[$i];
This line will be generating the reverse string and concatenating it with the variable $s. And since you are concatenating this variable $s (which already has some value abcdefg, you need to remove each characters from the variable which is done by the following line in your code:
$s[$i] = NULL;
You can check this by removing this line and check the output. It will output:
abcdefggfedcba
The simpler alternative would be to use strrev() function
follow this code
<?php
error_reporting(0);
$s = 'abcdefg';
$length = strlen($s);
$k=array();
for ($i = $length; $i>=0; $i--) {
$k .= $s[$i];
$k[$i] = NULL;
}
echo "$s";
echo "<br/>";
echo "there are <b>".$k."</b> character in the string.";
?>

Reverse string without strrev

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.
My first solution was something like this:
$s = 'abcdefg';
$temp = '';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$temp .= $s{$length - $i - 1};
}
var_dump($temp);
// outputs string(7) "gfedcba"
then they asked me if I could do this without doubling the memory usage (not using the $temp variable or any variable to copy the reversed string to) and I failed.
This kept bugging me and since then I tried to solve this multiple times but I constantly failed.
My latest try looks like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . $s;
}
var_dump($s);
// outputs string(14) "gfedcbaabcdefg"
It's not a solution to chop off "abcdefg" after the loop because then I would still double the amount of memory used. I need to remove the last character in every iteration of the loop.
I tried to use mb_substr like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . mb_substr($s, $length - $i - 1, 1);
}
var_dump($s);
but it only gives me Uninitialized string offset errors.
This is where I'm stuck (again). I tried googling but all the solutions I found either echo the characters directly or use a temporary variable.
I also found the Question PHP String reversal without using extra memory but there's no answer that fits my needs.
That's an interesting one.
Here's something I just came up with:
$s = 'abcdefghijklm';
for($i=strlen($s)-1, $j=0; $j<$i; $i--, $j++) {
list($s[$j], $s[$i]) = array($s[$i], $s[$j]);
}
echo $s;
list() can be used to assign a list of variables in one operation. So what I am doing is simply swapping characters (starting with first and last, then second-first and second-last and so on, till it reaches the middle of the string)
Output is mlkjihgfedcba.
Not using any other variables than $s and the counters, so I hope that fits your criteria.
You can use the fact that in PHP a string can be thought of as an array of characters.
Then basically what you want to do is to replace each character $i on the left side of the middle of the string with the character $j on the right side of the middle with the same distance.
For example, in a string of seven characters the middle character is on position 3. The character on position 0 (distance 3) needs to be swapped with the character on position 6 (3 + 3), the character on position 1 (distance 2) needs to be swapped with the character on position 5 (3 + 2), etc.
This algorithm can be implemented as follows:
$s = 'abcdefg';
$length = strlen($s);
for ($i = 0, $j = $length-1; $i < ($length / 2); $i++, $j--) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
}
var_dump($s);
$string = 'abc';
$reverted = implode(array_reverse(str_split($string)));
You could use the XOR swap trick.
function rev($str) {
$len = strlen($str);
for($i = 0; $i < floor($len / 2); ++$i) {
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
$str[$len - $i - 1] = $str[$i] ^ $str[$len - $i - 1];
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
}
return $str;
}
print rev("example");
Try this:
$s = 'abcdefg';
for ($i = strlen($s)-1; $i>=0; $i--) {
$s .= $s[$i];
$s[$i] = NULL;
}
var_dump(trim($s));
Here it is PHP7 version of this:
echo "\u{202E}abcdefg"; // outs: gfedcba
PHP strings are kinda-sorta mutable, but due to copy-on-write it's very difficult to modify them in-place without a copy being made. Some of the above solutions work, but only because they're stand-alone; some already fail because they define a function without a pass-by-reference argument. To get the code to actually operate in-place in a larger program, you'd need to pay careful attention to assignments, function arguments, and scopes.
Example:
$string1 = 'abc';
$string2 = $string1;
$string1[0] = 'b';
print("$string1, $string2");
> "abc, bbc"
I suppose that if between initializing the variable and modifying it you only ever used by-reference assignments (&=) and reference arguments (function rev(&$string)) (or assign the string to an object property initially, and then never assign it to any other variable), you might be able to change the original value of the string without making any copies. That's a bit ridiculous, however, and I'd assume that the interviewer who came up with that question didn't know about copy-on-write.
This isn't quite the same as immutability in other languages, by the way, because it applies to arrays too:
$a = [0, 1, 2];
$b = $a;
$b[0] = 1;
print(implode($a).implode($b));
> "012112"
To sum up, all types (except for objects as of PHP5) are assigned with copy-on-write unless you specifically use the &= operator. The assignment doesn't copy them, but unlike most other languages (C, Java, Python...) that either change the original value (arrays) or don't allow write access at all (strings), PHP will silently create a copy before making any changes.
Of course, if you switched to a language with more conventional pointers and also switched to byte arrays instead of strings, you could use XOR to swap each pair of characters in place:
for i = 0 ... string.length / 2:
string[i] ^= string[string.length-1-i]
string[string.length-1-i] ^= string[i]
string[i] ^= string[string.length-1-i]
Basically #EricBouwers answer, but you can remove the 2nd placeholder variable $j
function strrev2($str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
return $str;
}
Test for the output:
echo strrev2("Hi there!"); // "!ereht iH"
echo PHP_EOL;
echo strrev2("Hello World!"); // "!dlroW olleH"
This will go through the list and stop halfway, it swaps the leftmost and rightmost, and works it's way inward, and stops at the middle. If odd numbered, the pivot digit is never swapped with itself, and if even, it swaps the middle two and stops. The only extra memory used is $len for convenience and $tmp for swapping.
If you want a function that doesn't return a new copy of the string, but just edits the old one in place you can use the following:
function strrev3(&$str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
}
$x = "Test String";
echo $x; // "Test String"
strrev3($x);
echo PHP_EOL;
echo $x; // "gnirtS tseT"
Using &$str passes a direct pointer the the string for editing in place.
And for a simpler implementation like #treegardens, you can rewrite as:
$s = 'abcdefghijklm';
$len = strlen($s);
for($i=0; $i < $len/2; $i++) {
list($s[$i], $s[$len-$i-1]) = array($s[$len-$i-1], $s[$i]);
}
echo $s;
It has the similar logic, but I simplified the for-loop quite a bit.
Its Too Simple
//Reverse a String
$string = 'Basant Kumar';
$length = strlen($string);
for($i=$length-1;$i >=0;$i--){
echo $string[$i];
}
Here is my code to solve your problem
<?php
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i}.mb_substr($s,0,$i).mb_substr($s,$i+1);
}
var_dump($s);
?>
You could also use a recursion to reverse the string. Something like this for example:
function reverse($s) {
if(strlen($s) === 1) return $s;
return substr($s, strlen($s)-1) . reverse(substr($s , 0, strlen($s)-1));
}
What you do here is actually returning the last character of the string and then calling again the same function with the substring that contains the initial string without the last character. When you reach the point when your string is just one character then you end the recursion.
You can use this code to reverse a string without using the reserved function in php.
Code:
<?php
function str_rev($y)// function for reversing a string by passing parameters
{
for ($x = strlen($y)-1; $x>=0; $x--) {
$y .= $y[$x];
$y[$x] = NULL;
}
echo $y;
}
str_rev("I am a student");
?>
Output:
tneduts a ma I
In the above code, we have passed the value of the string as the parameter.We have performed the string reversal using for loop.
you could use substr with negative start.
Theory & Explanation
you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1 (which will convert the counter into negative value) and length of 1.
So for the first time counter would be 1 and by multiplying with -1 will turn it to -1
Hence substr('abcdefg', -1, 1); will get you g
and next iteration substr('abcdefg', -2, 1); will get you f
and substr('abcdefg', -3, 1); will get you e
and so on ...
Code
$str = 'abcdefghijklmnopqrstuvwxyz';
for($i=1; $i <= strlen($str); $i++) {
echo substr($str, $i*-1, 1);
}
In Action: https://eval.in/583208
public function checkString($str){
if(!empty($str)){
$i = 0;
$str_reverse = '';
while(isset($str[$i])){
$strArr[] = $str[$i];
$i++;
}
for($j = count($strArr); $j>= 0; $j--){
if(isset($strArr[$j])){
$str_reverse .= $strArr[$j];
}
}
if($str == $str_reverse){
echo 'It is a correct string';
}else{
echo 'Invalid string';
}
}
else{
echo 'string not found.';
}
}
//Reverse String word by word
$str = "Reverse string word by word";
$i = 0;
while ($d = $str[$i]) {
if($d == " ") {
$out = " ".$temp.$out;
$temp = "";
}
else
$temp .= $d;
$i++;
}
echo $temp.$out;
The following solution is very simple, but it does the job:
$string = 'Andreas';
$reversedString = '';
for($i = mb_strlen($string) - 1; $i >= 0; $i--){
$reversedString .= $string[$i];
}
var_dump($reversedString) then results: string(7) "saerdnA"
<?php
$value = 'abcdefg';
$length_value = strlen($value);
for($i = $length_value-1; $i >=0 ;$i--){
echo $value[$i];
}
?>
you can try this..
$string = "NASEEM";
$total_word = strlen($string);
for($i=0; $i<=$total_word; $i++)
{
echo substr($string,$total_word-$i,1);
}
i have used some built in function but without str_rev function .
<?php
$text = "red";
$arr = str_split($text);
$rev_text = array_reverse($arr);
echo join(" ",$rev_text);
?>
Try This
<?php
$str="abcde";
for($i=strlen($str)-1;$i>=0;$i--){
echo $str[$i];
}
?>
output
edcba
This is my solution to solve this.
$in = 'This is a test text';
$out = '';
// find string length
$len = strlen($in);
// loop through it and print it reverse
for ( $i = $len - 1; $i >=0;$i-- )
{
$out = $out.$in[$i];
}
echo $out;
Reverse string using recursion function.
$reverseString = '';
function Reverse($str, $len)
{
if ($len == 0) {
return $GLOBALS['reverseString'];
} else {
$len--;
$GLOBALS['reverseString'] .= $str[$len];
return Reverse($str, $len);
}
}
$str = 'Demo text';
$len = strlen($str);
echo Reverse($str, $len)
Try this
$warn = 'this is a test';
$i=0;
while(#$warn[$i]){
$i++;}
while($i>0)
{
echo $warn[$i-1]; $i--;
}

How can I print integer in triangle form

I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

Alphanumeric string increment using for loop

I have a two variable one is string contains number and another one is number,
I want increase the numeric part of string upto second number.
$n ='sh500';
$c = 3;
for($i=$n;$i<$c;$i++)
echo $i.'<br>';
I want output like:
sh500
sh501
sh502
Use $n++ where $n = 'sh500'. It works.
$n ='sh500';
$c = 3;
for($i = 0;$i < $c;$i++) {
echo $n++.'<br>';
}
Will output
sh500 <br>
sh501 <br>
sh502 <br>
It even works when ending with a alphanumeric character, because php converts it to the ASCII value of the character and adds one so a will become b and so on. But that's out of the scope of the question :)
$x="sh500";
$x = substr($x,0,2) . (substr($x,2) + 1);
echo $x;
echoes sh501 (works for any string having a number from 3rd character)
$n = 'sh';
for($i = 500; $i < 503; $i++) {
echo "$n$i\n";
}
$n="sh50";
for($i=0;$i<10;$i++){
$j=$n.$i;
echo $j."<br>";
}
it echo:
sh500
sh501
sh502
sh503
sh504
sh505
sh506
sh507
sh508
sh509
$n = 'sh500';
$c = 3;
$sh = substr($n,0,2); // will be "sh"
$number = substr($n,2,5) + 1; // will be "500"
for($i = $number; $i < 504; $i++) {
echo $sh.$i."\n";
}
Live demo: Here
if it is always a string of length 2 else use preg_match to find the first occurrence of a number.
http://www.php.net/manual/en/function.preg-match.php
$number = intval(substr($n, 2));
$number++;
echo substr($n, 0, 2) . $number;
$x = "sh500";
$s = substr($x, 0, 2);
$n = substr($x, 2);
$c = 3;
for ($i = $n; $i < ($n + $c); $i++)
{
echo $s.$i.'<br>';
}
OR another simple way is...
$n ='sh500';
$c = 3;
for ($i = 0; $i < $c; $i++) {
echo $n++."<br>";
}
Output
sh500
sh501
sh502

Stuck with the number pattern printing in PHP

Stuck with the number pattern printing logic. Let me know what i am doing wrong as my file is simply going on execution without giving me a pattern.
My Code --
<?php
$num = 4;
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num-1 ; $i++ )
{
echo " ";
}
for( $j ; $j >= 1 ; $j-- )
{
echo $j." ";
}
echo "<br />";
}
Pattern to achieve --
1
21
321
4321
UPDATE
After applying new changes following are the screenshots ---
for ($i = 1; $i <= 4; $i++) {
echo str_pad(implode('', range($i, 1)), 4, ' ', STR_PAD_LEFT) . '<br />';
}
Right aligned using CSS
echo '<div style="text-align:right;">';
for ($i = 1; $i <= 4; $i++) {
echo implode('', range($i, 1)) . '<br />';
}
echo '</div>';
Your error is in the last for, that should not exist since you are already looping.
And create a new variable which will hold the printed text for the next increment.
<?php
$num = 4;
$wrap = '';
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num ; $i++ )
{
echo " ";
}
echo $wrap = $j.$wrap;
echo "<br />";
}
?>
The fundamental reason is that a browser wont render multiple spaces only the first one, you can overcome this by using the non breaking space html entity &nbsp in place of spaces.
Soooo, If you want your actual pattern to look like:
1
21
321
4321
And not like:
1
21
321
4321
Use &nbsp (Edit: Tho actually use [space] as just 1 seems to not compensate for the width of the 1 char vs 4)
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).'<br />';
}
echo implode('',array_reverse($result));
?>
Or you could use a <pre> tag like:
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).PHP_EOL;
}
echo '<pre>'.implode('',array_reverse($result)).'</pre>';
?>
As it is right now, the problem lies in your third (or second nested) for loop.
You can't just reuse $j as a counter here, since $j is still being actively used in the encompassing for loop. Substitute that for loop with:
for( $k = $j ; $k >= 1 ; $k-- )
{
echo $k." ";
}
Here is the code for your program, You can go to Develepor hell for more such pattern
// Outer look for line change
for ($i = 1; $i<=5; $i++) {
// Loop added for spacing
for ($s = $i; $s<=10-$i; $s++) {
echo " ";
}
// Inner loop for printing required pattern
for ($j = $i; $j>=1; $j--) {
echo $j;
}
echo '</br>';
}
// Here is the code for your program,
// Pattern - 1
$num = 4;
// to print no. of rows
for( $i=1 ; $i <= $num ; $i++ )
{
// To print white space
for( $j=1 ; $j <= $num-$i ; $j++ )
{
echo "0";
}
// To print pattern
for( $z= $i ; $z>=1 ; $z-- )
{
echo $z;
}
// To print new line
echo "<br />";
}
==>> Output
0001
0021
0321
4321
//===================================================================//
Pattern - 2
$z=1;
$n=3;
# no of rows
for($i=1;$i<=$n;$i++)
{
# to check even or odd
if($i%2 == 0)
{
# main logic to display in reverse order // right to left
$z = ($z+$n) -1;
$a = $z;
for($j=1;$j<=$n;$j++)
{
echo $z--;
}
$z = $a+1;
}
else
{
# display data left to right
for($j=1;$j<=$n;$j++)
{
echo $z++;
}
}
echo "<br/>";
}
==>> Output
123
654
789
Your issue appears to be that you are printing your output into an HTML document which condenses multiple spaces as its default behavior. See "Why does HTML require that multiple spaces show up as a single space in the browser?" To "preserve" whitespaces while printing, use the <pre> tag.
I'll add a math-based solution instead of multiple iterated function calls and multiple loops (inspired by my explained answer here). Once your number limit gets higher than 9, I don't know if my output will align with your desired output.
Effectively, I use printf() to left-pad every line with spaces to the same max length. Each successive number prints the integer as many times as its value.
Code: (Demo)
$num = 4;
echo "<pre>";
for ($i = 1; $i <= $num; ++$i) {
printf("% {$num}d<br>", (10 ** $i - 1) / 9 * $i);
}
HTML Output (click on the eye icon in the demo link to switch to HTML mode):
1
22
333
4444
For comparison these also work inside of the for() loop (and offer a more intuitive result above 9):
printf("% {$num}d<br>", str_repeat($i, $i));
Or
echo str_repeat(' ', $num - $i) . str_repeat($i, $i) . "<br>";

Categories