-2

I'm trying to remove all the characters of a string AFTER a character appears 4 times, in this case the fourth appearance of character "/".

So if I have a string like this:

https://www.imbd.com/zenithasianfancyfood/posts

I want to get something like:

https://www.imbd.com/zenithasianfancyfood/
gabogabans
  • 3,035
  • 5
  • 33
  • 81

1 Answers1

1

Here we go, We can achieve this using explode function

  <?php
    $url = 'https://www.imbd.com/zenithasianfancyfood/posts';

    echo get_before_url_on_particlar_slash($url,4);
    
    function get_before_url_on_particlar_slash($url,$slash_position)
    {
        if(isset($url,$slash_position) && !empty($url))
        {
            $m = explode('/',$url);
            $s = '';
            foreach ($m as $k => $v)
            {
                if($k == $slash_position)
                {
                    break;
                }
                
                if($k == 0)
                {
                    $s .= $v.'//';
                }
                else
                {
                    $s .= $v.'/';
                }
                
            }
        }
        
        return rtrim($s,"/");
    }
?>

http://sandbox.onlinephpfunctions.com/code/a24389180a7cad014c62e9381d9caf9107c42092

Siddhartha esunuri
  • 1,104
  • 1
  • 17
  • 29