Drew
Drew

Reputation: 6862

PHP strstr() function replacement

Here is an example of how I am using strstr on my localhost on PHP 5.3.10

<?php
$string  = '25_testing';
$test = strstr($string, '_', true); // As of PHP 5.3.0
echo $test; // prints 25
?>

Well, I uploaded my files on my hosting server but they are running off of PHP 5.2 so the function strstr($string, '_', true) does not work. Is there an alternative I can use, to get the same results?

Upvotes: 1

Views: 5044

Answers (3)

Mattias
Mattias

Reputation: 9471

Try this...

First you return the string after "_" (including itself) and then replace it with nothing. Not very nice but it works ;)

<?php
    $string = "25_testing";
    echo str_replace(stristr($string,"_"),"",$string);
?>

or

<?php
    $string = "25_testing";
    echo str_replace(strstr($string,"_"),"",$string);
?>

Upvotes: 2

Jovan Perovic
Jovan Perovic

Reputation: 20193

You could use combination of strpos and substr:

<?php
$string  = '25_testing';
$test = substr($string, 0, strpos('_')); //maybe check if strpos does not return FALSE
echo $test; 
?>

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Drop the true, and slice the length of the needle off the end of the result.

Upvotes: 0

Related Questions