dragon201401 2013-12-18 13:45
浏览 90
已采纳

如何在从末尾匹配的字符串中获取模式的位置

$a = "this is school of sachin";
$pattern = "sch";

I want to get the position of the pattern matched from the end. For example in this case, sch matches school -- so the position of the pattern should be 3, i.e. from the end:

as mentioned below the index for the word school are arranged in this manner,so if the match of sch is successful than the position from the end of the word which is getting matched(school) and to the start of the pattern(from the end) should be returned.

s c h o o l
5 4 3 2 1 0

^---^

matched pattern.

I have tried strpos() but could not make it to serve my purpose.

echo strpos($a, $pattern); // this is wrong 

The output of strpos() should be 3 according to my question.

  • 写回答

4条回答 默认 最新

  • duanaoou4105 2013-12-18 13:53
    关注
    <?php
    $a = "this is school of sachin";
    $pattern = "sch";
    $words = explode(" ", $a);
    $pattern = strrev($pattern);
    foreach($words as $word){
    $pos = strpos(strrev($word), $pattern);
        if($pos !== false){
        print($pos);
        break;
        }
    }
    ?>
    

    OR

    <?php
    $a = "this is sachinùs school of sachin";
    $pattern = "sach";
    if(preg_match("/[^ [:punct:]]*".$pattern."([^ [:punct:]]*)/u", $a, $match)){
    print(mb_strlen($match[1], "UTF-8"));
        if($pattern == $match[0]){
        print(" (full word)");
        }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器