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
You can use
strtok()
to achieve this:If you ever needed the second value, you can call
strtok()
again:What about this with simple
explode()
and getting the0
th index ?Demo : https://eval.in/922189
The first line gives the length of first value and second line extracts it.