Jump to content

Recommended Posts

Hey everyone,

 

I am using strpos() to  find the position of a variable in a string, but I was wondering how i can find the position of a variable if its mentioned more than once, and one of the latter.

 

ex.

 

$string = 'There was a dog who was blue';

 

How can I find the position of the latter 'was', rather than the former one?

alternative method saves you an explode if you want the last one

<?php
$string = "There was a dog who was blue";
$needle = "was";
$needle = strrev($needle);
$pos_las = strpos($string,$needle,strlen($needle)-1);
echo "Position of last \"".strrev($needle)."\": ".$pos_las;
?>

Should work :)

There are lots of variations of how to derive the answer. I think this flexibility in php is what makes it so easy to learn. Take these other solutions for example:

 

<?php
echo "<br>";
$string = 'There was a dog who was blue';
$word = 'was';
$offset = strpos($string,$word);
$secondPos = strpos($string,$word,$offset+1)+1;
echo "The second position of the word \"$word\" in the string \"$string\" is at character number $secondPos.";
?>
<?php
echo "<br>";
$string = "There was a dog who was blue";
$revstring = strrev($string);
$needle = "was";
$revneedle = strrev($needle);
$pos_las = strlen($string) - strpos($revstring,$revneedle) - strlen($needle) +1;
echo "The last position of \"". strrev($needle) ."\" in the string \"$string\" is at character number $pos_las";
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.