dourou9477 2018-09-26 09:05
浏览 46
已采纳

如何使用str_replace或其他函数只更改字符串内的字符串一次?

I need to chnage some words inside strings - I must separate string on 2 or more words - or to add space before and after word. For example I have shopifystore - this must be separated into 2 words": shopify and store, so result must be: "shopify store". One more example - I have dogsstore - this must be separated into 2 words": dogs and store, so result must be: "dogs store"

So, I write some function, but results are not so good. My function:

function englishchange($string) {
$latin = array('dogs','dog','stores','store','shops','shop','shopify');
$latinchanged = array(' dogs ',' dog ',' stores ',' store ',' shops ',' shop ',' shopify ');
return str_replace($latin, $latinchanged, $string);
}
$englishchanged = (englishchange('shopifystore'));

But the resilt from "dogsstore" is: "dog s store" and "shopifystore" going to: "shop ify store". Can anyone help me, please, to rewrite php code to get the right result?

  • 写回答

2条回答 默认 最新

  • dongqie7806 2018-09-26 09:14
    关注

    You can use strtr in its second form to do the replacements. In that mode, it takes an array of replacement pairs and, working from the longest strings downward, having made a replacement, it will not replace that substring again. So you just need to combine your $latin and $latinchanged arrays into an array using array_combine and then call strtr:

    function englishchange($string) {
    $latin = array('dogs','dog','stores','store','shops','shop','shopify');
    $latinchanged = array(' dogs ',' dog ',' stores ',' store ',' shops ',' shop ',' shopify ');
    return strtr($string, array_combine($latin, $latinchanged));
    }
    $englishchanged = (englishchange('dogsstore shopifystore'));
    echo $englishchanged;
    

    Output:

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

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误