Search code examples
phpstringsubstr

PHP How to get string before special character?


I'm trying to get from this string:

UPS EXPRESSS_SAVER - 1 día hab.

the portion of: EXPRESSS_SAVER

I tried the following code: It starts from 4 index of the string and finishes before special character "-"

$shippingMethod = "UPS EXPRESSS_SAVER - 1 día hab.";
$shippingServiceId = substr($shippingMethod, 4, strpos($shippingMethod,'-'));

This returned me: EXPRESSS_SAVER - 1

I also tried :

$shippingServiceId = substr($shippingMethod, 4, strpos($shippingMethod,' '));

But got: EXP


Solution

  • You can use below code dot get EXPRESSS_SAVER

    $shippingMethod = "UPS EXPRESSS_SAVER - 1 día hab.";
    
    $shippingMethodArr = explode(" ",$shippingMethod);
    
    $shipped = $shippingMethodArr[1];