Remove a comma between two specific characters
I currently have the string:
"Blah, blah, blah,~Part One, Part Two~,blah blah"
开发者_JAVA技巧
I need to remove the comma between the ~
character so it reads.
"Blah, blah, blah,~Part One Part Two~,blah blah"
Can anyone help me out please?
Many thanks,
If there is exactly one comma between the ~
s and an even number of ~
s in all, then
preg_replace("/~([^,]*),([^,]*)~/", "~\1\2~", $text)
should do it.
It may be easier to do this in a few steps:
- Split on
~
- Transform the parts that are "inside" the
~
only- Simply replace
','
with''
- Simply replace
- Join the parts back together with
~
A regex solution
That said, it is possible to do this in regex, assuming an even number of ~
:
<?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're at the beginning of the string, "outside"
- Just match until we find the first
~
, so next time we'll be "inside" - So,
(^[^~]*~)
- Just match until we find the first
- There are no more
~
till the end of the string- If there are even number of
~
, we'll be "outside" - Just match until the end
- So,
([^~]*$)
- If there are even number of
- If it's none of the above, we're "inside"
- Keep finding the next comma before
~
(so we're still "inside")- So,
([^,~]*),
- So,
- If we find
~
instead of a comma, then go out, then go back in on the next~
- So,
([^,~]*~[^~]*~)
- So,
- Keep finding the next comma before
In all case, we make sure we capture enough to reconstruct the string.
References
- regular-expressions.info/Character Classes, Anchors, Grouping and backreferences
$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;
It does the job, but I wrote it right here and might have problems (at least performance problems).
精彩评论