Jump to content
Larry Ullman's Book Forums

Recommended Posts

The php.net page is way to technical but I was wondering if anyone could help me understand how the strrpos() function works. I've only been learning php for about 2 months so my knowledge is very basic to

php. In question was using strrpos() using 2 arguments verses 3 arguments eg ............ strrpos($string, 0, 1); So far im up to chapter 12 in the book. =)

Thanks All In advance.

jp

 

p.s. if my example doesn't make sense, that's cause i don't know what im talking about.

Link to comment
Share on other sites

So the function's signature looks like this:

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

To start, the int means the function returns an integer. The first two arguments are strings and are required. The function will try to find $needle in $haystack and will return the indexed position where $needle begins in $haystack.

If you don't provide the third argument, the search will start at the beginning of $haystack. So 'cat' will be found in 'catastrophe'. The third argument, $offset, is an integer indicating a different starting place. For example, 'cat' will not be found in 'catastrophe' if the offset is anything other than 0: if offset is 1, then the net effect would be looking for 'cat' in 'atastrophe'.

  • Upvote 1
Link to comment
Share on other sites

Hi Larry Thank you for your explanation. So If I am understaning correctly.

 

$haystack = catastrophe;

$needle = 3;

$string = strrpos($haystack, $needle);

 

echo "$string"; // value would be 'cat'

 

or

$string = strrpos($haystack, $needle, 1);

 

echo "$string"; // value would be 'ata'

thanks

jp

Link to comment
Share on other sites

No, you're not quite there. First of all, the $needle of 3 would never be found in 'catastrophe'. Second, strrpos() returns a number, not a string. Third, strrpos() only returns a number if the needle is found within the haystack. Also, you don't need to use quotes if you're just printing the value of a variable:

echo $var;

Link to comment
Share on other sites

Ok I think I got it now. It returns an integer of the postion starting at 0 from the left

<?php


$name = "JaePee_is_cool.always";

$var = strrpos($name, '.'); // $var would have a value of 15
if ($var) { // true because $var = 15
   $name = substr($name, 0, $var); // would extract JaePee_is_cool
   }
   echo $name; // will print JaePee_is_cool

 

is this correct?

 

Thank you very much for your time and help..

Jp

Link to comment
Share on other sites

Thanks Larry, The code works. I understand it now a little more. I have enjoyed your book. Keep up the great work, I really appreciate your personal help, and all the great help here on the forum. I will definitely pay it forward if I ever get the chance to.

 

jp

 

 

Link to comment
Share on other sites

 Share

×
×
  • Create New...