我有一个名为$DiscountDescriptionTrimmed的变量,它可能包含以下格式的数据:
免费快速航运俱乐部会员,A63540678,
或
A63540678,
我想在这个变量中找到礼品卡的编号(例如: A63540678),并在此基础上执行逻辑,将'Gift Card‘附加到$DiscountDescription的开头。
目前,我的代码只考虑礼品卡号码是否在变量的前面。如果它在任何其他位置(例如,在逗号之后),则不会。
肯定有一种RegEx方法可以让这段代码做得更好,对吧?我有各种礼品卡场景,下面在我的代码中列出,这些场景主要由以特定字母或数字开头的礼品卡组成,并且具有一定的长度。
我当前的PHP代码是:
$Description = $item->getName();
$DiscountDescription = $_order->getDiscountDescription();
$DiscountDescriptionTrimmed = strtok($DiscountDescription,', ');
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);
}
}礼品卡场景:
场景一:礼品卡以"e“开头,长度为11个字符。
场景2:礼品卡以"E“开头,长度为9个字符。
场景3:礼品卡以"A“开头,长度为9个字符。
场景4:如果礼品卡有17个字符,其中有两个"-“破折号。
场景5:如果礼品卡有8个字符,并且只包含数字。
发布于 2018-01-23 15:28:44
任务是
(1)从字符串中过滤出卡号;
(2)不同场景下使用卡号。这是我为你准备的:
$DiscountDescriptionTrimmed = "Free and Fast Shipping Club Member, A63540678, ";
$pattern = '/^(e[a-zA-Z]{10})|(E[a-zA-Z]{8})|(A[a-zA-Z]{8})|([a-zA-Z\-]{16})|([0-9]{8})/';
preg_match($pattern, $DiscountDescriptionTrimmed, $match);
for($i=1; $i<=5; $i++) {
$len = strlen($match[$i]);
if($len < 1) {
continue;
} else {
// Scenario $i as you shown in the question
/* for example */
$_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
break;
}
}(e[a-zA-Z]{10}),e+ 10个字母
(E[a-zA-Z]{8}),E+8个字母
(A[a-zA-Z]{8}),A+8字母
([a-zA-Z\-]{16}),16个字母+ '-‘
([0-9]{8}),8个数字
如果卡号仅由数字组成,而不是字母(字符不明确),则将[a-zA-Z]替换为[0-9]
如果是混合类型,则使用[0-9a-zA-Z]
发布于 2018-01-23 15:49:55
试试下面的代码。希望能对你有所帮助。
$text = "e7867445537, Free and Fast Shipping Club Member, A63540678, e7678 , Free and Fast Shipping Club Member, E67485536 , ET66U-UIK-66eh6YY,
ET66UuUIKd66eh6YY, 99887765";
function remove_zero($matches)
{
return 'Gift Cards ' .$matches[0];
}
echo preg_replace_callback(
"/(([\d]{8}?)|([A][\d]{8}?)|([e][\d]{10}?)|([E][\d]{8}?)|(([\w]*[-]{1}[\w]*[-]{1}[\w]*)([\S]{17})?))([\D\W]|$)/",
"remove_zero",
$text);发布于 2018-01-23 15:26:21
我不知道PHP,但快速搜索一下它的文档就会发现,它使用perl风格的正则表达式语法,还具有执行搜索和替换的函数,例如函数preg_replace。我找到的文档位于here,你看过文档了吗?如果你有,它对你没有帮助吗?
https://stackoverflow.com/questions/48395922
复制相似问题