Given this code:
$text = "This is a string";
$lookup = " "; // This string contains a single space!
$pos = strlen($text) - 1;
echo substr_rev_pos($text, $lookup, $pos);
the function below will look inside $text for any single character from $lookup, and it will start at position $pos, going back toward the first character.
When it finds such a character, it will return the part of $text that precedes it, including the character that was found.
If it does NOT find such a character, it'll return the first $pos characters of $text.
function substr_rev_pos($string, $needles, $index)
{
if(strlen($string) > $index)
{
for($i = $index - 1; $i >= 0; --$i)
{
if(strpos($needles, $string{$i}) !== false)
{
return substr($string, 0, $i + 1);
}
}
}
return substr($string, 0, $index);
}