skip to Main Content

I have a string called $DiscountDescription that can sometimes be populated with data like this:

A43544675, A33540055,

Or like this:

A43544675, 

Basically, I can have either one value or two values within it, separated by a comma. I really only need the first value. If there’s only one value, it always has a comma and a space after it, which is why in my code below I’m removing the comma and space to evaluate the string.

My current code is below. You can see where I’m only accounting for this if there’s one value in the string, but not both. So what I’d like to do is find the comma, and grab everything to the left of the comma, and make that equal to $DiscountDescriptionTrimmed.

$DiscountDescription = $_order->getDiscountDescription();

$DiscountDescriptionTrimmed = substr_replace($DiscountDescription ,"",-2);

if ($DiscountDescriptionTrimmed != '') {
    if (substr($DiscountDescriptionTrimmed,0,1) === "e" && strlen($DiscountDescriptionTrimmed) === 11){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescriptionTrimmed,0,1) === "E" && strlen($DiscountDescriptionTrimmed) === 9){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescriptionTrimmed,0,1) === "A" && strlen($DiscountDescriptionTrimmed) === 9){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescriptionTrimmed) === 17 && substr_count($DiscountDescriptionTrimmed,'-') === 2){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescriptionTrimmed) === 8 && ctype_digit($DiscountDescriptionTrimmed)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }

}

3

Answers


  1. You can use strtok() to achieve this:

    $DiscountDescriptionTrimmed = strtok($DiscountDescription, ', ');
    

    If you ever needed the second value, you can call strtok() again:

    $SecondDiscountDescriptionTrimmed = strtok(', ');
    
    Login or Signup to reply.
  2. What about this with simple explode() and getting the 0 th index ?

      $DiscountDescription1 = 'A43544675, A33540055,';
      $DiscountDescription2 = 'A43544675,';
      echo explode(',',$DiscountDescription1)[0];
      echo "n";
      echo explode(',',$DiscountDescription2)[0];
    

    Demo : https://eval.in/922189

    Login or Signup to reply.
  3. The first line gives the length of first value and second line extracts it.

    $length = strpos($DiscountDescription, ',') + 1;
    $DiscountDescriptionTrimmed = substr($DiscountDescription, 0, $length);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search