Regex find ampersands without spaces on either side

I'm just trying to figure out a regex to find any ampersands that don't immediately precede, and then a space. For example, he will find "asdf & asdf" and "asdf & asdf", but not "asdf and asdf"

This will be used in preg_replace to add spaces before and after. (If you're curious, the problem is that I'm stuck with WYSIWYG, which has an error where it separates spaces from both sides of ampersands, and I need to manually add them back after the fact). Thoughts?

+4
php regex
source share
8 answers

The ampersand width is not after a space or the ampersand is not before a space, but not for both:

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

Use lookaround so that it only captures the ampersand.

+4
source share
 (\S&\S|\s&\S|\S&\s) 
  • No char spaces followed by another non-space char
    OR
  • A space followed by &, then a space char
    OR
  • Without char spaces followed by &, then char spaces follow
+5
source share

To place a space, if it is missing on both sides, can be done as follows:

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

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

 echo preg_replace('/(?<! )&(?! )/',' & ','asdf&asdf asdf& asdf asdf & asdf'); //asdf & asdf asdf& asdf asdf & asdf 
+1
source share

Ampersand with a space after or after:

 (&[^ ]|[^ ]&) 
+1
source share

I suggest that you first find all ampersands that are independent of the characters on the left and right, and then use a negative appearance for the statement to ensure that both characters are not spaces.

 .&.(?<! & ) 
+1
source share
 ([^\s]+&.+)|(.+&[^\s]+) 

This regular expression ensures that there is no space on the left side to the right of the &

0
source share

It should work (not verified): /([^\s]&|&[^\s])/ . If you are only concerned with spaces, and not "any empty character": /([^ ]&|&[^ ])/

0
source share
 (?<=\s)\&\&\s 

https://regex101.com/r/vBuuUf/1

hope this helps

0
source share

All Articles