Simon Smith
Simon Smith

Reputation: 8044

Can I trim start and end whitespace from PHP's shell_exec() output?

I'm running shell_exec (git log in this example) and my response has a lot of whitespace at the start and end of the string.

                    7baca58 test 3
847ad88 test 3
bcd7340 Nother test
21a5f17 Testing git releases
8faa1c0 Add previously ignored files in attempt to push to server with git

I have tried $string = preg_replace('/\s+/', ' ', $string); but this also removes the line breaks as well. Normal trim also doesn't seem to help.

How can I just remove the leading and trailing spaces?

Upvotes: 0

Views: 1162

Answers (2)

mallix
mallix

Reputation: 1429

Remove spaces and tabs, should keep line breaks, try it:

$string = preg_replace("/[ \t]+/", " ", $string);

For only spaces remove the \t

Upvotes: 1

jasir
jasir

Reputation: 1471

Your regexp $string = preg_replace('/\s+/', '', $string); will replace all whitespaces. To trim whitespaces from begining and end of string, try trim(). If you need to trim all lines from your string, try

$s = '';
foreach(explode("\n", $lines) as $line) {
    $s. = trim($line);
}

Upvotes: 0

Related Questions