Remove the comma between two specific characters

I currently have a line:

"Blah, blah, blah,~Part One, Part Two~,blah blah" 

I need to remove the comma between the ~ character so that it reads.

 "Blah, blah, blah,~Part One Part Two~,blah blah" 

Can anyone help me out?

Many thanks,

+6
string php regex
source share
3 answers

If there is exactly one comma between ~ and an even number ~ , then

 preg_replace("/~([^,]*),([^,]*)~/", "~\1\2~", $text) 

must do it.

+6
source share

It can be easier to do in a few steps:

  • Divide by ~
  • Convert only the parts that are inside ~
    • Just replace ',' with ''
  • 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")
      • So, ([^,~]*),
    • If instead of a comma to find ~ , then exit, and then return to the next ~
      • So, ([^,~]*~[^~]*~)

In all cases, we make sure that we commit enough to restore the string.

References

+1
source share
 $string = "Blah, blah, blah,~Part One, Part Two~,blah blah"; $pos1 = strpos($string, "~"); $substring = substr($string, $strpos, strlen($string)); $pos2 = strpos($string, "~"); $final = substr($substring, $pos1, $pos2); $replaced = str_replace(",", "", $final); $newString = str_replace($final, $replaced, $string); echo $newString; 

He does the job, but I wrote it right here and might have problems (at least performance issues).

0
source share

All Articles