It can be easier to do in a few steps:
- Divide by
~ - Convert only the parts that are inside
~ - Connect the parts together with
~
Regular solution
However, this can be done in regex, assuming an even number ~ :
<?php echo preg_replace( '/(^[^~]*~)|([^~]*$)|([^,~]*),|([^,~]*~[^~]*~)/', '$1$2$3$4', 'a,b,c,~d,e,f~,g,h,i,~j,k,l,~m,n,o~,q,r,~s,t,u' ); ?>
The above prints ( as seen on codepad.org ):
a,b,c,~def~,g,h,i,~jkl~m,n,o~qr~s,t,u
How it works
There are 4 cases:
- We are at the beginning of the line, "outside"
- Only match until we find the first
~ , so next time we will be "inside" - So
(^[^~]*~)
- More
~ to the end of the line- If there is a number
~ , we will be "outside" - Match up to the end
- So
([^~]*$)
- If it is not, we are "inside"
- Keep finding the next comma before
~ (so we are still "inside") - If instead of a comma to find
~ , then exit, and then return to the next ~
In all cases, we make sure that we commit enough to restore the string.
References
polygenelubricants
source share