开发者

PHP Find Previous String Position

Is there a way that I can search a variable starting from a given position and find the start position of a string that is in the variable backwards from the given start position.

So for example if I initially do $getstart = strpos($conten开发者_高级运维ts, 'position', 0);

I then want to do $getprevpos = prevstrpos($contents, 'previous token', $getstart);

Obviously there is no such function as prevstrpos but I hope you get what I mean.

Example text area (terrible example I now): Here is an example where I want to find the previous token once I have found the start position of a text string.


you can strrpos( substr($contents, 0, $getstart), 'previous token')


Is there something wrong with strrpos()? If 'offset' is negative: "Negative values will stop searching at the specified point prior to the end of the string."


you can try this. I think it should would for all cases but you should probly test it a bit. Might be a bug here and there but you get the idea. Reverse everything and do a strpos on the reversed string

prevstrpos( $contents, $token, $start )
{
  $revToken = strrev($token);
  $revStart = strlen($token) - $start;
  $revContent = strrev($content);
  $revFoundPos = strpos( $revContent, $revToken, $revStart );
  if( $revFoundPos != -1 )
  {
    $foundPos = strlen($token) - $revFoundPos;
  }
  else
  {
    $foundPos = -1;
  }
  return $foundPos;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜