普通网友 2014-08-24 17:15
浏览 20
已采纳

用偏移量找到任意一个字符的位置 - php?

I'm trying to find the position of any of a number of characters, but need to be able to set a search offset.

This is precisely the functionality of strpos() but matching any of a number of characters rather than a single string/character. If strpos() would accept an array of $needles it would be exactly what I need (assuming it returns the position of the earliest match in $haystack).

strpbrk() has exactly what's needed in terms of matching a set of characters, but this does not allow an offset so that I can move along the string after each successful match.

This seems an odd thing to be missing from the PHP string functions, is there something I am missing?

Here is a code summary:

  while($pos=strpos($el->text(), '*_-!`' ,$el->position())!==FALSE){
      $el->position($pos);

       foreach ($HandlerTypes as $Type){
          // Note: $el->position is modified within this function
          $this->markSpan($Type, $el);
       }
   }

Where I'm looking for any of *, _, -, ! or ` rather than the string of them. Any marker might appear more than once in the string.

thanks.

  • 写回答

1条回答 默认 最新

  • duanlvji4780 2014-08-24 17:27
    关注

    Regular expressions to the rescue!

    $s = 'skipbfoobarxarjar';
    preg_match_all('~[bxj]~', $s, $m, PREG_OFFSET_CAPTURE, 5);
    print_r($m[0]);
    

    Result:

    [0] => Array
        (
            [0] => b
            [1] => 8
        )
    
    [1] => Array
        (
            [0] => x
            [1] => 11
        )
    
    [2] => Array
        (
            [0] => j
            [1] => 14
        )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历