php how replace characters before and after special characters

时间:2018-12-05 18:05:00

标签: php string

I have a php string like:

$string = '1234532323%A73823823221A%221312373712';

the string has numbers and 2 special tags (%A and A%) to indicate the begin and the end of the special part, respectively.

My goal is to replace all "1" with "2", but not in the part of the string between %A and A%.

If I use strtr(string,"1","2") all 1 occurrences will be replaced. Does anyone know how my goal can be achieved?

Special characters may appear several times inside the string.

2 个答案:

答案 0 :(得分:0)

您可以通过将它们分开并替换字符串来做到这一点。确实要研究preg_*才能更好地解决所有情况。

$a = "1234532323%A73823823221A%221312373712";
//explode to an array of 3 objects
$b = explode('%',$a);
//replace the numbers in the first and last object
$b[0] = strtr($b[0],"1","2");
$b[2] = strtr($b[2],"1","2") ;
//concatenate them again to get $a
$a = $b[0].$b[1].$b[2];

echo($a);

答案 1 :(得分:0)

那么您可以使用此算法

  

注意:它不是用任何编程语言编写的

int test = 0;
for(int i=0;i<ch.length();i++){
  if(test!=1 && ch(i)!="%"){
   if(ch(i)==1)
    ch(i)=2;
  }else
  {
   test++;
  }
}

不好意思,表示抱歉。