PHP doesn't detect white space in string - php

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);

Related

PHP is automatically removing whitespace I want to keep

I have a string I want to process which looks like this:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Note how there are multiple spaces between characters. The number of spaces is important, and thus I don't want them to be discarded. When I read this line from a file using php, it prints the following:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Maintaining only a single space where there were several before. How can I stop PHP from doing this?
Ultimately I want to substring the entire thing into an array of individual characters but I need the array position to be preserved.
Thank you!
EDIT: Example of what I'm talking about:
Replace it with the html entity for a non breaking space to view it rendered in browser's html
<?php
$str = ' HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH';
$str = str_replace(' ',' ',$str);
echo $str;
If you're viewing it with a browser you could use HTML to keep the formatting intact. For instance:
echo '<pre> HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH</pre>';
See: http://www.w3schools.com/tags/tag_pre.asp
I think <code> might also work.

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 Insert Multiple Spaces

I've got some data that needs to be cleaned up into a fixed length format. I'm using PHP to grab the data out, covert it, and put it back in, but it's not working as planned. There is a certain point in each piece in the middle of the data where there should be spaces to increase the length to the proper amount of characters. The code I'm using to do this is:
while ($row = mysql_fetch_array($databasetable)) {
$key = $row['KEY'];
$strlength = strlen($key);
while ($strlength < 33) {
$array = explode(' TA',$key);
$key = $array[0] . ' TA' . $array[1];
$strlength++;
}
}
It's taking a ' TA' and adding two spaces before it, rinse and repeat until the total length is 33, however when I output the value, it just returns a single space. Funny part is that even though it is displaying a single space, it returns a strlen of 33 even if it's not displaying 33 characters.
Any help in figuring this out would be greatly appreciated.
HTML will have extra spaces filtered out.
To force extra spaces to be shown, use ' ' rather than ' '.
#TVK- is correct, HTML ignores multiple-space whitespace - it'll turn it into one space.
In addition to his solution, you can use the CSS instruction white-space: pre to preserve spaces.
Remember that, when doing an output to a webbrowser, it'll interpret it as HTML ; and, in HTML, several blank spaces are displayed as one.
A possibility would be to use the var_dump() function, especially if coupled with the Xdebug extension, to get a better idea of your data -- or to display it as text, sending a text-related content-type.
BTW : if you want to make sure a string contains a certain amount of characters, you'll probably want to take a look at str_pad()
Easiest options for you I think are
Wrap your output in <pre> tags
replace each space with
If you're rendering HTML, consecutive spaces will be ignored. If you want to force rendering of these, try using
Generally using multiple non breakable spaces one after another is a bad idea and might not bring a desired result unless you're using a monospaced font. If you want to move some piece of text to a certain position on your page, consider using margins
You can tell the browser that the text is preformatted
this text will be displayed as it is formatted
spaces should all appear.
new lines will also be apparent
Have you looked into str_pad? something like :
str_pad ( 'mystring' , 33 , ' TA' , STR_PAD_LEFT );
I thing you can use str_repeat
echo str_repeat(" ", 15);

Trying to remove "»" with php

I'm trying to remove this character, and this character only from a $string with php. I've tried str_replace("»","",$test) and str_replace(chr(187),"",$test) but they can't touch it. The issue is it isn't in the same spot every time, so I can't even get creative with trimming the ends.
Are you forgetting that str_replace(old, new, string) doesn't modify the original string, but rather returns a copy of the modified string?
So:
$string = "This is the » character";
$new_string = str_replace("»", "_", $string);
echo $new_string;
Should work (it does for me)!
Wanted to point out that "»" in HTML equals » which is a standard. So, my advise would be that you better use standard characters.
Reference of characters: http://www.w3schools.com/tags/ref_entities.asp
I ended up stepping through the string one character at a time with
echo ord($test[n]
until I finally found the offending hidden character that was ruining my night.
Thanks for all the help everyone!

PHP "backspace" character during output possible?

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.

Categories