4

I'm looking to get the same exact results as php strstr command (while it set to true) but in reverse order.

I know that I can simply reverse the string and use strstr and then reverse it again

but I was wonder if there is any internal php command for the task.

<?php

$myString = 'We don\'t need no education';

echo strstr($myString, ' ', true);

/*
 * output :
 * We
 *
 * I'm expecting to get :
 * education
 *
 */

exit;

?>

Very Simple !

Steven
  • 249
  • 5
  • 14

4 Answers4

7

You have the function strrchr

$myString = 'We don\'t need no education';

echo strrchr($myString, ' ');
// output : ' education'

echo substr(strrchr($myString, ' '), 1);
// output : 'education'
Pezhvak
  • 9,633
  • 7
  • 29
  • 39
Alfwed
  • 3,307
  • 2
  • 18
  • 20
  • This answer is partly misleading. `strrchr` is **not** a reverse `strstr`. As the [official documentation](https://secure.php.net/manual/en/function.strrchr.php) states, `strrchr` searches for the last occurence of a *character* in the string, not for any string. If the needle passed to `strrchr` contains more than one character, only the first one is used. Luckily because OP searches for one character only, this worked here. – Neonit Aug 15 '17 at 08:17
  • @Neonit removed the misleading part – Pezhvak Aug 20 '21 at 13:59
2

From http://php.net/manual/en/function.strstr.php#103577 (in the comments)

function rstrstr($haystack,$needle)
{
    return substr($haystack, 0, strpos($haystack, $needle));
}

Author: Dennis T Kaplan

Jazi
  • 6,569
  • 13
  • 60
  • 92
1

You can do the following:

   $myString = 'This is a string';
   $words = explode(' ', $myString);
   $lastWord = array_pop($words);

Wrap it in a function

function lastWord($string) {
   return array_pop(explode(' ', $string));
}

Is this helping you further.

Paul Oostenrijk
  • 659
  • 8
  • 16
  • array_pop expects the parameter to be a reference to an array it can manipulate... so in some versions of php it won't accept the expression and you'll have to declare a variable. – SparK May 22 '17 at 23:56
0

using str :

$basename = strrev(substr(strchr(strrev($postfile_name),'.'),1)); 
//test.php will return test

$ext = strrchr( $postfile_name, '.' ); 
//test.php will return .php
sixbad
  • 1