Search code examples
phpsubstrstrstr

remove before specific string not character


Format of string is as follow

$img = "/images/posts/main.jpg";
$img1 = "/images/posts/john.jpg";

I need to remove /images/posts/ and echo rest of the content.

I tried with strstr, But I found it deals with only character

echo strstr($img, '/images/posts/')
//output => /images/posts/main.jpg

if I use only single character echo strstr($img, '/') Then output is images/posts/.

So I use substr with strstr to get expected result.

echo substr(strstr($img, '/'), 14);
//output => main.jpg

In my case, I am sure it will work constantly with same result because the part images/posts/ remains same and will not change.

But is it really good or fast way to counting and trimming ? Any other fast way to cut /images/posts/ at once ?

Or replace ? is it faster ??

echo str_replace('/images/posts/','',$img);

Solution

  • You can do like this..

    Syntax-

     str_replace(find, replace, string, count) 
    

    For Eg-

    str_replace('/images/posts/', '', '/images/posts/main.jpg');
    

    it will print main.jpg