dongzhanyan3667 2018-12-05 18:05
浏览 108

php如何替换特殊字符前后的字符

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条回答 默认 最新

  • du656637962 2018-12-05 18:29
    关注

    You can do that by breaking them apart and replacing the strings. do look into preg_* to better solve all cases.

    $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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据