12

Imagine i have this string :

$info="portugal,alemanha,belgica,porto 1-0 alemanha, belgica 2-0";

I want to know the position of the 2nd char "-", so i want the result 2-0 and not the result 1-0.

I'm using this function, but it's always returning the first position,

$pos = strpos($info, '-');

Any idea? Thanks

unpix
  • 853
  • 2
  • 15
  • 31
  • See also https://stackoverflow.com/questions/3126324/question-about-strpos-how-to-get-2nd-occurrence-of-the-string/18589825 – caw Dec 30 '18 at 01:49

3 Answers3

26

Simplest solution for this specific case is to use the offset parameter:

$pos = strpos($info, '-', strpos($info, '-') + 1);

You might want to look into using regular expressions, though.

Rijk
  • 11,032
  • 3
  • 30
  • 45
  • 6
    shouldn't it be "strpos($info, '-', strpos($info, '-')+1)"? – Jesse Aug 13 '13 at 14:44
  • just tested, it behaves well even if the string contains zero or just one character. e.g: returns false as expected with no errors. – d.raev Jan 10 '17 at 12:09
  • 2
    For some search strings (`$needle`) you may need `+ strlen($info)` instead of just `+ 1`. – caw Dec 30 '18 at 01:49
8

Try this

preg_match_all('/-/', $info,$matches, PREG_OFFSET_CAPTURE);  
echo $matches[0][1][1];
user1835851
  • 112
  • 2
  • 16
    Try not to answer with just a block of code: add some description of your solution. – Artemix Nov 21 '12 at 13:36
  • worked, now to understand, you put the regular expression '/-/', so the char '/' represent some char before - and after, right? What is the meaning of PREG_OFFSET_CAPTURE? and why $matches[0][1][1] Thank you for the solution – unpix Nov 21 '12 at 14:24
  • 7
    Old thread, but this is largely unhelpful due to a lack of explanation on how to navigate the data, so I'll provide it: Firstly, the PREG_OFFSET_CAPTURE flag turns the results into an array that captures the position of the found string. To get the first match, you'd use $matches[0][0], the third match you'd use $matches[0][2], etc. In this case, $matches[0][1] gets the second match. That match is (thanks to PREG_OFFSET_CAPTURE) an array with two values. $matches[0][1][0] returns just the string that was found ("-"). $matches[0][1][1] returns the position/offset of that string. – Tom Walker Jul 14 '16 at 22:53
0

You have to use offset parameter

$pos = strpos($info, '-', [offset]); 

It will work perfectly.

Andreas
  • 23,610
  • 6
  • 30
  • 62
som
  • 4,650
  • 2
  • 21
  • 36
  • 15
    `offset` specifies the number of characters to skip before looking, not the number of `needle` occurrences to skip – Leigh Nov 21 '12 at 12:29