Page 1 of 1

Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 6:51 am
by m8kwr
Hi,

I am very new to expressions, and i am trying to do the following, if its at all possible.

If i have the following string:

<col caption = 'Contact Name';columns = contacts.salutation, contacts.first_name,

I would like to remove the spaces and ' marks, but leave the spaces if they are contain between ' (if this symbol cause a problem then i am willing to chance it to something else)

So it looks like;

<colcaption=Contact Name;columns=contacts.salutation,contacts.first_name,

Many thanks

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 7:09 am
by prometheuzz
Try this:

Code: Select all

echo preg_replace(
  "/\s(?=([^']*'[^']*')*[^']*$)|'/i", 
  '', 
  "<col caption = 'Contact Name';columns = contacts.salutation, contacts.first_name, "
);

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 8:25 am
by m8kwr
many thanks for the reply, works great, apart from not removing the ' - but leaving in the space between them.

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 8:28 am
by prometheuzz
m8kwr wrote:many thanks for the reply, works great, apart from not removing the ' - but leaving in the space between them.
You're welcome.
But it also removes the single quotes from it. I tested the regex with:

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 8:39 am
by m8kwr
Hi,

I used http://regexlib.com/RETester.aspx, and i have regexbuddy - but it doesn't remove the ' in there....

Am i doing something wrong. Sorry i am very new to regex's

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 8:41 am
by m8kwr
sorry it was me, i forgot to remove the /i, and it is all working perfectly now, many thanks again.

Re: Removing spaces, but not if contained within a single quote

Posted: Thu Dec 04, 2008 8:54 am
by prometheuzz
m8kwr wrote:sorry it was me, i forgot to remove the /i, and it is all working perfectly now, many thanks again.
No problem, and you're welcome.