101

I need to remove all characters from any string before the occurrence of this inside the string:

"www/audio"

Not sure how I can do this.

2

4 Answers 4

205

You can use strstr to do this.

echo strstr($str, 'www/audio');
Sign up to request clarification or add additional context in comments.

1 Comment

Quick note: you can use strstr() to return the part of the string that comes before its argument too by calling echo strstr($str, 'www/audio', true);
24

Considering

$string="We have www/audio path where the audio files are stored";  //Considering the string like this

Either you can use

strstr($string, 'www/audio');

Or

$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];

3 Comments

string functions are generally faster than array functions
The explode is in fact a better answer, as the question was about removing the text before the string.
explode could cause problems if you had multiple occurrences of the same string you were trying to remove - e.g. "we have www/audio path where the www/audio files are stored" would result in "path where the" if you wanted to use explode you could do something like foreach ( $expStr as $key => $value ) echo ( $key == 0 ? '' : 'www/audio'.$value ) ; or foreach ( $expStr as $key => $value ) echo ( $key == 0 ? '' : ( $key == 1 ? '' : 'www/audio' ).$value ) ; if you wanted to omit the initial www/audio.
2

I use this functions

function strright($str, $separator) {
    if (intval($separator)) {
        return substr($str, -$separator);
    } elseif ($separator === 0) {
        return $str;
    } else {
        $strpos = strpos($str, $separator);

        if ($strpos === false) {
            return $str;
        } else {
            return substr($str, -$strpos + 1);
        }
    }
}

function strleft($str, $separator) {
    if (intval($separator)) {
        return substr($str, 0, $separator);
    } elseif ($separator === 0) {
        return $str;
    } else {
        $strpos = strpos($str, $separator);

        if ($strpos === false) {
            return $str;
        } else {
            return substr($str, 0, $strpos);
        }
    }
}

2 Comments

This works well for multiple occurrences of the same string. Thanks!
for right remove - from the substr to get complete string after the first occurance of the seperator
0

You can use substring and strpos to accomplish this goal.

You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.