Search code examples
phpstringexplodetrimsubstr

Trim string until specified character and also trim suffix


I don't know if this is possible using trim, substr or explode. What I have is a echo that prints this type of a string (it's actually a breadcrumb)

Choose > Apples > Green > Wholesale > 5KG boxes

Is it possible to chop the string so it prints only

Apples > Green 

The structure of the breadcrumbs is fixed, so I will always want to chop the first part (Choose >) and the last two parts (> Wholesale > 5KG boxes) so I need to chop everything until the first ">" character and everything after the 3rd ">" character including the characters.


Solution

  • The easiest way to solve this is by exploding the string into an array. After that you just print the two items you need.

    $string = 'Choose > Apples > Green > Wholesale > 5KG boxes';
    $stringParts = explode(' > ', $string);
    $newString = $stringParts[1].' > '.$stringParts[2];