Removing spaces, but not if contained within a single quote

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
m8kwr
Forum Newbie
Posts: 4
Joined: Thu Dec 04, 2008 6:48 am

Removing spaces, but not if contained within a single quote

Post 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
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

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

Post by prometheuzz »

Try this:

Code: Select all

echo preg_replace(
  "/\s(?=([^']*'[^']*')*[^']*$)|'/i", 
  '', 
  "<col caption = 'Contact Name';columns = contacts.salutation, contacts.first_name, "
);
m8kwr
Forum Newbie
Posts: 4
Joined: Thu Dec 04, 2008 6:48 am

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

Post by m8kwr »

many thanks for the reply, works great, apart from not removing the ' - but leaving in the space between them.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

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

Post 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:
m8kwr
Forum Newbie
Posts: 4
Joined: Thu Dec 04, 2008 6:48 am

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

Post 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
m8kwr
Forum Newbie
Posts: 4
Joined: Thu Dec 04, 2008 6:48 am

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

Post by m8kwr »

sorry it was me, i forgot to remove the /i, and it is all working perfectly now, many thanks again.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

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

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