PHP "backspace" character during output possible? - php

I have a feeling the answer is "it's not possible," but thought I'd ask to satisfy my curiosity.
I have some code that's echoed where the \n is unavoidable:
echo "Hello \n";
echo "World!";
I'd like the line to simply read (in the code output):
Hello World!
... thus removing the \n.
So I was wondering if it's possible to execute a "backspace" character during PHP's output?
Something simple like str_replace( "\n", 'backspace-character', $str );

Yes, the backspace character is ASCII character code 8 (According to the ASCII table), so you can output it in php using chr(). eg:
echo 'ab' . chr(8);
will output "a"

If the output target is HTML then extra spaces don't matter - browsers don't render multiple, contiguous spaces (which is why we have )
If the output target is something else, then you can simply cleanup the output. As you can see from other replies, there are a myriad of ways to do this. It seems like you're working with echo statements so the output-buffering functions will be the route you want to take.
ob_start();
echo "Hello \n";
echo "World!";
$output = preg_replace( "/ +/", ' ', str_replace( "\n", ' ', ob_get_clean() ) );
echo $output;

If you wanted to be able to do it for anything you could use the output buffer:
ob_start();
echo "Hello\n World";
$out = ob_get_contents();
ob_end_clear();
echo str_replace('\n', '', $out);
You could even use httaccess to append scripts containing this to any script called.
However, couldn't you just deal with it before it is set to stdout? Like
function print2($str){
echo str_replace("\n", '', $str);
}

This is not a direct answer to his exact question, but to what the title seems to allude to: outputting a PHP "backspace" character, which is probably only useful when using the PHP CLI.
You can find the right ASCII code for this (and other characters) on the ASCII table, and then use either chr() or an escape sequence:
echo chr(8);
echo "\010";

What about just replacing the "\n" by a white space (or just nothing, if you already have one space in your incoming string) ?
Like this, for instance :
$str = "Hello\nWorld!";
var_dump($str);
$str = str_replace("\n", ' ', $str);
var_dump($str);
The first output gives :
string 'Hello
World!' (length=12)
And the second one :
string 'HelloWorld!' (length=11)
Is that not enough ?
(Or maybe I don't understand the question well)

Can't you do it like this:
$str = str_replace("\n", ' ', $str);
while (strpos($str, ' ') !== false) // while there's two spaces in a row
$str = str_replace(' ', ' ', $str);
Now $str will have every spaces or \n characters sequences replaced by only one space.
(because if you just remove \n you migth have some place where a space is missing, and if you just replace it by a space you'll have some places with multiple spaces in a row).
EDIT: i don't know if the loop is really necessary but i don't have anything to test here if str_replace will automatically do the trick (and i don't think using regexp for such a simple thing is really a good idea).

Instead of thinking about how to do a backspace character, I would suggest rethinking the problem. Why do you want to take back some of your output? Probably because you outputted it too early.
Instead of doing an echo on the intermediary values, append them to the buffer. Then edit the buffer. Then print it out. If you can't control whether the output is produced or not (for example, you're using external vendor's library that outputs stuff), use PHP output buffering.

I don't know how to do a backspace, but if you are just trying to do a new line I would use:
echo "<br>";
PHP code allows for html code as long as it is used in a print or echo statement and is inside double quotes.

Related

substr and strip_tags character issue and solution

I'm calling same text for php but result is chracter problem. e.g;
"<div class="open"><?php echo ex_substr(180); ?></div>"
and run the function
function ex_substr($char) {
$title= get_the_excerpt($post->ID);
$title= strip_tags(substr($title,0,$char));
echo $title."...";
}
At the end of the text content,there are character problems for example: �
I'm very new about php.
as I said in the comments when you see weird stuff like � you probably have some weird non UTF-8 characters in there.
While I am by no means an expert at encodings ( typical I just remove that junk ) This is what I use to deal with them
preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
Here is a PHP sandbox you can try it in.
http://sandbox.onlinephpfunctions.com/code/695ad38ae46ef5a142102dd6150fd84279b1a058
$string ='this is a string �';
echo preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
Output
'this is a string '
You can smack it with trim($string) if that extra space at the end bugs you.
Another trick is to replace it with a space . and then remove any multiple spaces. That way if it's between words it doesn't just jam them together.
$string ='this is a�string';
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', ' ', $string);
echo trim( preg_replace('/\s{2, }/', ' ', $string)); //replace 2 or more spaces with a single space.
Even when the DB charset set to UTF-8 I occasionally get weird stuff in my DB. We have a lot of content that is scrapped off the web so who knows what that crap is.
This is sort of a "rudimentary" way to fix it, but if you're not worried about loosing those characters than it should be fine. I should study up more on encoding issues, now that I don't have PHP6 to fix all that for me.
( PS from what i understand PHP6 was supposed to have more support for multi=byte strings, but because of the short comings of C it all fell apart, which is why we went from PHP5 to PHP7 )
Hope that helps.
$title= strip_tags(substr($title,0,$char));
instead of
$title= mb_substr($title,0,$char);
The problem is completely resolved when I use it.

Trim does not strip spaces

I've read plenty of answers but never found a solution.
Why doesn't this work with trim?
$test = trim('Whatever this is');
echo $test;
This work:
$test= preg_replace('/\s+/', ' ', 'Whatever this is');
echo $test;
Expected:
Whatever this is
Why doesn't the first one work, when the second one does? No strange characters as I write them directly in the PHP code.
Please don't close this one too quickly
trim strips spaces only from beginning and end of a string. Please refer this link.

jquery html() losing spaces

I'm testing a preg_replace function, and I return from an ajax function the processed data (after I process the data through preg_replace, I put it through htmlentities() ):
My test string is:
pr eg123 ~!##$%^&*()-+={}|[]:;< >? "...,'/...
I'm trying to make sure all those characters aren't replaced. My replace function is:
$string = preg_replace('/[^a-zA-Z0-9\s+\n\r,.\/~!##\$%\^&*()\+={}\[\]|:;<>?\'"-]/', '', $string);
I return both the data from "echo" and after going through htmlentities() to see the difference.
when I return the data using alert(data), I get:
pr eg123 ~!##$%^&*()-+={}|[]:;< >? "...,'/...
pr eg123 ~!##$%^&*()-+={}|[]:;< >? "...,'/...
respectively. However, when I put either of those into $("#div").html(data), I get:
pr eg123 ~!##$%^&*()-+={}|[]:;< >? "...,'/...
so the multiple spaces are lost. Why does the .html() function reduce the spaces? And how can I fix this? Thanks
remove "\s+" from your regular expression and try again
"I'm trying to make sure all those characters aren't replaced." you mean it?
so i make a test like below:
$string = "~!##$%^&*()-+={}|[]:;< >?";
// $string = preg_replace('/[^a-zA-Z0-9]/', '', $string);
echo "'", $string, "'";
output is
'~!##$%^&*()-+={}|[]:;< >?'
if you want keep whole white space between "<" and ">" in $string, i can say that no way, if you wanna output the same white spaces as you input: there are two way can make this:
1> use <pre> tage
2> use replace the white space
does you want these? if you want to keep all? why use regular?

PHP doesn't detect white space in string

I'm working on transferring data from one database to another. For this I have to map some values (string) to integers and this is where I run into a strange problem.
The string looks like this $string = "word anotherword"; so two words (or one space).
When I explode the string or count the amount of spaces it misses the white space. Why? I var_dumped the variable and it says it's a string.
Below is the code i'm using.
echo "<strong>Phases</strong>: ".$fases = mapPhase($lijst[DB_PREFIX.'projectPhase']);
The string that's being send to the function is for example "Design Concept". This calls the following function (where the spaces get ignored)
function mapPhase($phases){
echo "Whitespace amount: ".substr_count($phases, ' ')."<br />";
}
For the example string given this function echoes 0. What's causing this and how can i fix it? The strangest thing is that for one instance the function worked perfectly.
More than one whitespaces (in HTML) are always converter into one whitespace. For example code indents.
If you want to print more than one, one by one use &nbps; instead.
function mapPhase($phases){
echo 'Whitespace amount: '.substr_count($phases, ' ').'<br />';
}
It may well be that the alleged space in the string may not be a space as in ' ', but something similar, which gets rendered in the browser in the same way as ' ' would. (for a rudimentary list of possible characters: http://php.net/manual/en/function.trim.php)
Thus, checking what the whitespace exactly is may be the solution to that problem.
Maybe they are not even spaces. Try ord() for each symbol in your string.
ord(' ') is 32.
You can use:
$string = preg_replace('/\s+/', '', $string);

PHP, why sometimes "\n or \r" works but sometimes doesnt?

Well, I am abit confuse using these \r,\n,\t etc things. Because I read online (php.net), it seems like works, but i try it, here is my simple code:
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo $str . $str2;
?>
But the outcome is "My name is jingle I am a boy"
Either I put the \r\n in the var or in the same line as echo, the outcome is the same. Anyone knows why?
Because you are outputting to a browser, you need to use a <br /> instead, otherwise wrap your output in <pre> tags.
Try:
<?php
$str = "My name is jingle <br />";
$str2 = "I am a boy";
echo $str . $str2;
?>
Or:
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo '<pre>' .$str . $str2 . '</pre>';
?>
Browsers will not <pre>serve non-HTML formatting unless made explicit using <pre> - they are interested only in HTML.
Well in your example you've got \n\r rather than \r\n - that's rarely a good idea.
Where are you seeing this outcome? In a web browser? In the source of a page, still in a web browser? What operating system are you using? All of these make a difference.
Different operating systems use different line terminators, and HTML/XML doesn't care much about line breaking, in that the line breaks in the source just mean "whitespace" (so you'll get a space between words, but not necessarily a line break).
You could also use nl2br():
echo nl2br($str . $str2);
What this function does is replace newline characters in your string to <br>.
Also, you don't need \r, just \n.
In HTML, spaces, tabs, linefeeds and carriage returns are all equivalent white space characters.
In text, historically the following combinations have been used for newlines
\r on Apple Macs
\r\n on Windows
\n on Unix
Either use \n (*NIX) or \r\n (DOS / Windows), \n\r is very uncommon. Once you fix that, it should work just fine.
Of course, if you're outputting HTML, a line break does nothing unless it's inside <pre></pre> tags. Use <br /> to separate lines in HTML. The nl2br() function can help you to convert line breaks to HTML if needed.
Also, if you use single-quoted strings (your example has double quoted strings), \r and \n will not work. The only escape characters available in single quoted strings are \' and \.
Are you displaying the results in an HTML page? if so, HTML strips whitespace like newlines. You'd have to something like use '<br />' instead of '/r/n' in HTML.

Categories