Jump to content

[SOLVED] Finding the position of a variable


Sesquipedalian

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";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.