tags:

views:

273

answers:

7

I'm just trying to figure out the regex to find any ampersands that aren't immediately preceded and followed by a space. For example, it would find "asdf&asdf" and "asdf& asdf" but not "asdf & asdf"

This will be used in a preg_replace to add spaces before and after. (If you're wondering, the problem is that I'm stuck with a WYSIWYG that has a bug where it strips spaces on both sides of ampersands, and I need to manually add them back after the fact). Thoughts?

+1  A: 

To put space if it is not there on either side, can be done like this

echo preg_replace('/ ?& ?/',' & ','asdf&asdf asdf& asdf asdf & asdf');
//asdf & asdf asdf & asdf asdf & asdf

For without spaces on both sides (Answering to question title), it will fail on asdf& asdf

echo preg_replace('/(?<! )&(?! )/',' & ','asdf&asdf asdf& asdf asdf & asdf');
//asdf & asdf asdf& asdf asdf & asdf
S.Mark
Mike Hanson
Paul Lammertsma
Note that the OP wants a regex that matches an ampersand without space on one side _or_ the other (not necessarily both).
Paul Lammertsma
According to my tests, I finds only strings with a space neither before nor after. What he wants is ampersands without both, not ampersands with neither.
Mike Hanson
I've put all three test strings into RegexBuddy, and it matches only the one with no spaces (the first one).
Mike Hanson
Added another one, the question title is confusing actually.
S.Mark
+1  A: 

Ampersand with non-space after or before:

(&[^ ]|[^ ]&)
Mike Hanson
Kobi
A: 
([^\s]+&.+)|(.+&[^\s]+)

This regex makes sure that there is no space on the left xor the right of an & character

Matt Ellen
Frank Farmer
Fair point. Will work on it
Matt Ellen
Have updated to make it work.
Matt Ellen
+4  A: 
(\S&\S|\s&\S|\S&\s)
  • Non whitespace char, followed by & and another non space char
    OR
  • Whitespace followed by &, followed by non space char
    OR
  • Non whitespace char followed by &, followed by another whitespace char
Amarghosh
To complete the answer, I believe the solution will be: `preg_replace('/(\S`
Frank Farmer
+4  A: 

Ampersand width not after a space or ampersand not before a space, but not both:

(?<!\s)&|&(?!\s)

Using lookaround, so this captures the ampersand only.

Kobi
+1, this is neater than mine.
Amarghosh
+1  A: 

I suggest to first find all ampersands independent of the characters to the left and right and then use a negative look behind assertion to ensure that not both characters are spaces.

.&.(?<! & )
Daniel Brückner
A: 

It should work (not tested) : /([^\s]&|&[^\s])/. If you are only concerned about spaces and not "any blank character" : /([^ ]&|&[^ ])/

Arkh