Page 1 of 1

preg_replace and possible json issues

Posted: Wed Jun 11, 2014 2:55 am
by babyskill
I need to replace a whitespace at the beginning of any newline. I am using JSON to send over the POST values and suspect this may have something to do with it not working.

Code: Select all

$str='
This is a string.
   This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^\s+/', '', $str);
Running this, works as expected. When I attempt to use it with my JSON POST array, the whitespaces remain.

Does JSON play a part in this?

Re: preg_replace and possible json issues

Posted: Wed Jun 11, 2014 7:00 am
by Celauran
babyskill wrote:

Code: Select all

$str='
This is a string.
   This should be left justified by removing whitespaces preceding it.
';
preg_replace('/^\s+/', '', $str);
Running this, works as expected.
I don't expect that to work at all. $str doesn't begin with a space.

Re: preg_replace and possible json issues

Posted: Wed Jun 11, 2014 12:24 pm
by requinix
That will only remove the newline you have at the beginning of the string. If you want ^ to match the beginning of any line then you need the /m flag.

Code: Select all

echo preg_replace('/^\s+/m', '', $str);
You are using json_encode(), right?