SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Level 8 Chinese guy Archbob's Avatar
    Join Date
    Sep 2001
    Location
    Somewhere in this vast universe
    Posts
    3,741
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Is there a function to find the position of the nth occurence of something in sting?

    Hi,
    Say I have a big paragraph, I want to find the position of the 7th period in the string?

    In the past I've just compared letter by letter to see if it is a period, and if it is, added one. Is there a function in PHP to do it.

  2. #2
    SitePoint Enthusiast mrsmiley's Avatar
    Join Date
    Jul 2004
    Location
    Melbourne
    Posts
    96
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There isn't a single function that can do that that I'm aware of, but you could keep calling strpos to search for it and make use of the offset parameter.

    Or, thinking a little outside the box here:

    <?php
    $test = 'z.x.c.v.b.n.h.g.f';

    $parts = explode('.', $test);
    for($i=count($parts); $i>7; $i--)
    unset($parts[$i]);

    $pos = strlen(implode($parts, '.'));
    ?>

    Totally untested, but it should work. Just split the string based on the . character, then delete any array entries past the number of occurances you are looking for, then join the string back up and count the number of characters in it. The result might be out by one character.

  3. #3
    Level 8 Chinese guy Archbob's Avatar
    Join Date
    Sep 2001
    Location
    Somewhere in this vast universe
    Posts
    3,741
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah, its for pagination for a long paragraph, so it involves getting stuff between periods 30 and 60 and so on. I know how to do it, was just wondering if there's a more efficient way. Arrays start at index 0 right?

  4. #4
    SitePoint Addict
    Join Date
    Mar 2005
    Location
    Toronto
    Posts
    378
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can't suggest a more efficient way, hope anyone much better at php could though I would like to know this as well. And yep array index always starts at 0.
    In search of the clouds...and maybe some work


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •