preg_replace and possible json issues

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
babyskill
Forum Newbie
Posts: 7
Joined: Tue Jan 19, 2010 10:07 am

preg_replace and possible json issues

Post 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?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: preg_replace and possible json issues

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: preg_replace and possible json issues

Post 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?
Post Reply