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.
Related
I'm taking this file and splitting it up into sentences. The issue is that its formatted weirdly. I need to remove all the random new lines, indentations and unneeded spaces. Is there a way to do this with php?
I am currently using
$test= file_get_contents("text.txt");
$stringtest = str_replace(PHP_EOL,'', $test);
But I am getting weird behavior when I try to split up the sentences. Is there a way to do this?
The weird behavior is that when I print out the text
echo $stringtest;
There are unseen characters between lines where a newline/weird_spacing used to exist.
You can use a regex to merge all whitespaces to a single space. Also you probably want to remove whitespace at the beginning and end. Try this:
$test = trim($test);
$test = preg_replace('/\s+/s', ' ', $test);
Let's say I have a variable $foo:
$foo = " a a blablabla a a";
But when I do var_dump($foo) the following gets outputted:
string(57) " a a blablabla a a"
It's like the length (57 in this case) it's correct and it counts the spaces, but it doesn't display them.
How can I display the full string, including the multiple spaces in between the other characters?
If you use <pre> tag the text appears in the brower as you typed it. Couple of links:
http://www.tizag.com/htmlT/htmlpre.php
http://www.htmlcodetutorial.com/linepar/_PRE.html
You could also replace spaces with non breaking space .
Web browsers ignore a lot white space in the code which is nice. Otherwise we wouldn't be able to intend our source code or use newlines much...
Are you by any chance doing this in a browser. If so you need to do this.
<pre>
<?php echo var_dump($foo); ?>
</pre>
Because I just tried in command line and I get the output with spaces. Browsers don't handle multiple spaces and they trim them down. If you want a browser to handle multiple spaces you have to use the output inside a <pre> tag or use instead of spaces.
something like echo str_replace(' ', ' ',$test);
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);
What's the best way to remove these tags from a string, to prepare it for being passed to eval() ?
for eg. the string can be something like this:
<?php
echo 'hello world';
?>
Hello Again
<?php
echo 'Bye';
?>
Obviously str_replace won't work because the two php tags in the middle need to be there (the the 1st and the last need to be removed)
Usually, you wouldn't want to pass a function to eval.
If you're wishing to just remove the tags, string_replace would do the job just fine, however you might be better off using a regex.
preg_replace(array('/<(\?|\%)\=?(php)?/', '/(\%|\?)>/'), array('',''), $str);
This covers old-asp tags, php short-tags, php echo tags, and normal php tags.
Sounds like a bad idea, but if you want the start and end ones removed you could do
$removedPhpWrap = preg_replace('/^<\?php(.*)(\?>)?$/s', '$1', $phpCode);
This should do it (not tested).
Please tell me also why you want to do it, I'm 95% sure there is a better way.
You could do:
eval("?> $string_to_be_evald <?");
which would close the implicit tags and make everything work.
There's no need to use regex; PHP provides functions for removing characters from the beginning or end of a string. ltrim removes characters from the beginning of the string, rtrim from the end of the string, and trim from both ends.
$code = trim ( $code );
$code = ltrim( $code, '<?php' );
$code = rtrim( $code, '?>' );
The first trim() removes any leading or trailing spaces that are present in the siting. If we omitted this and there was whitespace outside of the PHP tags in the string, then the ltrim and rtrim commands would fail to remove the PHP tags.
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.