I have this:
$text = '
hello world
hello
';
How do I remove
only if it is on its own line? So with above example, the second
should be removed. Results should be:
$text = '
hello world
hello
';
Via str_replace()
, I can:
$text = str_replace(' ', '', $text);
But that will remove all instances of
, not only when it's on its own line.
I've already tried this approach and I get the output you want
// Your initial text
$text = '
hello world
hello
';
// Explode the text on each new line and get an array with all lines of the text
$lines = explode("\n", $text);
// Iterrate over all the available lines
foreach($lines as $idx => $line) {
// Here you are free to do any if statement you want, that helps to filter
// your text.
// Make sure that the text doesn't have any spaces before or after and
// check if the text in the given line is exactly the same is the
if ( ' ' === trim($line) ) {
// If the text in the given line is then replace this line
// with and emty character
$lines[$idx] = str_replace(' ', '', $lines[$idx]);
}
}
// Finally implode all the lines in a new text seperated by new lines.
echo implode("\n", $lines);
My output on my local is this:
hello world
hello
My approach would be:
Resulting in the following code:
$chunks = explode(PHP_EOL, $text);
$chunks = array_map('trim', $chunks);
foreach (array_keys($chunks, ' ') as $key) {
$chunks[$key] = '';
}
$text = implode(PHP_EOL, $chunks);
Maybe something like this:
$text = preg_replace("~(^[\s]?|[\n\r][\s]?)( )([\s]?[\n\r|$])~s","$1$3",$text);
http://sandbox.onlinephpfunctions.com/code/f4192b95e0e41833b09598b6ec1258dca93c7f06
(that works on PHP5, but somehow doesn't work on some versions of PHP7)
Alternative would be:
<?php
$lines = explode("\n",$text);
foreach($lines as $n => $l)
if(trim($l) == ' ')
$lines[$n] = str_replace(' ','',$l);
$text = implode("\n",$lines);
?>
If you know your end of line chars, and your
is always followed by a new line:
<?php
$text = '
hello world
hello
';
print str_replace(" \n", "\n", $text);
Output (some intial whitespace lost in the formatting here):
hello world
hello
Caveat: Any line that ends with a
with other content preceeding would also be affected, so this may not meet your needs.
You can use a regular expression for this, using the DOTALL and MULTILINE modifiers together with look-around assertions:
preg_replace("~(?sm)(?<=\n)\s* (?=\n)~", '',$text);
(?sm)
: DOTALL (s) MULTILINE (m)(?<=\n)
: preceeding newline (not part of the match) \s* \s*
: single with optional surrounding whitespace(?=\n)
: trailing newline (not part of the match)>>> $text = '
hello world
hello
';
=> """
\n
hello world\n
\n
hello\n
"""
>>> preg_replace("~(?sm)(?<=\n)\s* \s*(?=\n)~", '',$text);
=> """
\n
hello world\n
\n
hello\n
"""
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With