doufeng5059 2015-06-08 07:40
浏览 69
已采纳

PHP str_replace不能给我想要的输出

I want to replace a string at a particular position. For that I used str_replace() PHP function, but after that, I can't get an output. Here I show you what I want.

$str = "hello 8-7-2015 world -12";
// here I want replace - with ' desh ' but in date only. That I have detected using check before character if space than it should be 'minus' otherwise it should be 'desh'.

$key = strpos($str, "-");
if($key !== false){
     $a = substr($str, $key-1 , 1);
     if($a != " "){
           $str = str_replace("-","desh",$str);
     }else{
           $str = str_replace("-","minus",$str);
     }
}

I get output like: hello 8 desh 7 desh 2015 world desh 12 . Everywhere there is desh I want minus 12. Other values are okay and should not be changed. Means particular position change.

  • 写回答

4条回答 默认 最新

  • drhzc64482 2015-06-08 07:52
    关注

    Your code (with an if) doesn't loop over the string looking for all occurrences, so that should have raised an alert flag with you when all the occurrences were changed.

    What it does is to find the first occurrence, which isn't preceded by a space, then it executes:

    str_replace("-","desh",$str);
    

    which replaces all occurrences within the string. In order to do what you want, all you need is:

    str_replace(" -"," minus",$str);
    str_replace("-","desh",$str);
    

    This will first take care of all - character preceded by a space, turning them into " minus".

    The second line will then take care of all the remaining - characters, replacing them with "desh".


    Just as an aside, if you're doing this to be able to "speak" the words (in the sense of a text-to-speech (TTS) program), you probably want spaces on either sides of the words you're adding. You can achieve that with a very small modification:

    str_replace(" -"," minus ",$str);
    str_replace("-"," desh ",$str);
    

    That may make it easier for your TTS code to handle the words.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)