duanchijie2323 2014-06-10 23:45
浏览 23
已采纳

PHP - 在句子的两个位置之间搜索和替换

I'm trying to replace 'he' by 'she' between two given positions, in this case between Maria(0) and Peter(34). So basically I give two positions and replace all the occurrences in the sentence between the boundaries. I have tried with the following simple code but it seems that the substr_replace function doesn't allow me to do it. Any idea to make it works?

$sentence = "Maria went to London where he met Peter with his family.";
$clean = substr_replace($sentence, "he", "she", 0, 34);
  • 写回答

2条回答 默认 最新

  • douping5226 2014-06-10 23:54
    关注

    You are using substr_replace() incorrectly, and in this case you don't need it. Instead, try this, using a combo of str_replace() and substr():

    $sentence = "Maria went to London where he met Peter with his family.";
    $clean = str_replace(' he ', ' she ', substr($sentence, 0, 34));
    $clean .= substr($sentence, 34);
    

    See demo

    Essentially, you are replacing he with she on the specified substr of $sentence, then concatenating the rest of $sentence back on.

    Note the spaces around ' he ' and ' she '. This is necessary because otherwise you would replace where with wshere.

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100