Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove term only if it is on its own line

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

What I've tried so far

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.

like image 779
Henrik Petterson Avatar asked Feb 12 '20 10:02

Henrik Petterson


5 Answers

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
like image 137
KodeFor.Me Avatar answered Nov 06 '22 17:11

KodeFor.Me


My approach would be:

  1. Explode text on new lines
  2. Trim each value in the array
  3. Empty each array item with value  
  4. Implode with new lines

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);
like image 41
JanP Avatar answered Nov 06 '22 16:11

JanP


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) == '&nbsp;')
            $lines[$n] = str_replace('&nbsp;','',$l);
    $text = implode("\n",$lines);
?>
like image 2
Flash Thunder Avatar answered Nov 06 '22 16:11

Flash Thunder


If you know your end of line chars, and your &nbsp; is always followed by a new line:

<?php
$text = '
   hello&nbsp;world
   &nbsp;
   &nbsp;hello
';


print str_replace("&nbsp;\n", "\n", $text);

Output (some intial whitespace lost in the formatting here):

   hello&nbsp;world

   &nbsp;hello

Caveat: Any line that ends with a &nbsp; with other content preceeding would also be affected, so this may not meet your needs.

like image 1
Progrock Avatar answered Nov 06 '22 17:11

Progrock


You can use a regular expression for this, using the DOTALL and MULTILINE modifiers together with look-around assertions:

preg_replace("~(?sm)(?<=\n)\s*&nbsp;(?=\n)~", '',$text);
  • (?sm): DOTALL (s) MULTILINE (m)
  • (?<=\n): preceeding newline (not part of the match)
  • \s*&nbsp;\s*: single &nbsp; with optional surrounding whitespace
  • (?=\n): trailing newline (not part of the match)
>>> $text = '                                                                                               
 hello&nbsp;world                                                                                         
 &nbsp;                                                                                                   
 &nbsp;hello                                                                                           
 ';
=> """
   \n
      hello&nbsp;world\n
      &nbsp;\n
      &nbsp;hello\n
   """
>>> preg_replace("~(?sm)(?<=\n)\s*&nbsp;\s*(?=\n)~", '',$text);
=> """
   \n
      hello&nbsp;world\n
   \n
      &nbsp;hello\n
   """
>>>
like image 1
Tom Regner Avatar answered Nov 06 '22 16:11

Tom Regner