dsla94915 2017-10-21 20:19
浏览 35
已采纳

如何跳过strrpos Entry

Is it possible to skip a strpos/strrpos position?

    $string = "This is a cookie 'cookie'.";
    $finder = "cookie";
    $replacement = "monster";
    if (strrpos($string, $finder) !== false)
        str_replace($finder, $replacement, $string);

I want to skip the 'cookie' and replace the plain cookie so it'll result in "This is a monster 'cookie'."

I don't have qualms with it finding 'cookie' first and then checking it (Obviously necessary to determine it shouldn't be replaced), but I want to make sure that while 'cookie' is still there, I can use the same function to find the unquoted cookie.

Alternatively, is there a function I haven't found yet (Through hours of searching) to get all indices of a particular word so I can check them all through a loop without the use of regex?

It's important that it's the index, not the word itself, as there are other checks that have to be done based on where in the string the word's located.

  • 写回答

3条回答 默认 最新

  • duandu5846 2017-10-21 22:22
    关注

    The following gives the required replacement as well as the position of the replaced word.

    $string = "This is a cookie 'cookie'."; 
    $finder = "cookie";
    $replacement = "monster";
    $p = -1; // helps get position of current word
    $position = -1; // the position of the word replaced
    $arr = explode(' ',$string);
    for($i = 0; $i < count($arr); $i += 1){
    // Find the position $p of each word and
    // Catch $position when a replacement is made
    if($i == 0){$p = 0;} else {  $w =$arr[$i - 1]; $p  += strlen($w) + 1;}
    if($arr[$i] == $finder){ if($position < 0){$position = $p;}$arr[$i] = $replacement;}}
    $newstring = implode(' ', $arr);
    echo $newstring; // gives: This is a monster 'cookie'
    echo '<br/>';
    echo $position;  // gives 10, the position of replaced element.
    

    For the position, the assumption is that the sentence has only single spaces because spaces are used in the explode and implode functions. Otherwise a case of double or larger spaces would require modifications, possibly by replacing spaces with a unique character or set of characters such as @$# which would be used as the first argument of the explode and implode functions.

    The code could be modified to capture more than one replacement, e.g. by capturing each replaced position in an array instead of testing for if(position < 0). This would also require to change the way $position is computed because its values are affected by the lengths of previous replacements.

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

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行