Как получить все строки с соответствующими текстами в php - PullRequest
1 голос
/ 26 января 2020

У меня есть строка для практики.

$message = "Hurray! You've received a $100 Amazon Gift Card. Hope you enjoy this Amazon Gift Card! What's next? Apply the gift card to your Amazon account:=20 https://www.amazon.com/g/ Don't have an Amazon account? Sign up to redeem: www.amazon.com You can also redeem your gift card at checkout using this claim code: NE7N-TUD6NV-GUAB We hope to see you again soon, Amazon.com Once applied to your Amazon account, the entire amount will be added to you= r gift card balance. Your gift card balance can't be transferred to other a= ccounts, used to buy other gift cards, or, except as required by law, redee= med for cash. Your gift card balance will be applied automatically to eligible orders dur= ing the checkout process and when using 1-Click. If you don=E2=80=99t want = to use your gift card balance on your order, you can unselect it as a payme= nt method in checkout.=20 If you experience any issues using your gift card, you can reference your g= ift card by providing the following information to Customer Service: Order Number: 234343433433";

Я хочу получить код претензии, используя preg_match, но мне не удается. Это мой код.

 if(preg_match_all("/claim code:.*\s/", $message, $array)){
           print_r($array);
       }

вывод был такой

Array ( [0] => Array ( [0] => claim code: ) ) 

Но я хочу показать код претензии, кто-нибудь может помочь?

Ответы [ 2 ]

2 голосов
/ 26 января 2020

Я бы использовал шаблон (?<=\bclaim code: )\S+:

$message = "Hurray! You've received a $100 Amazon Gift Card. Hope you enjoy this Amazon Gift Card! What's next? Apply the gift card to your Amazon account:=20 https://www.amazon.com/g/ Don't have an Amazon account? Sign up to redeem: www.amazon.com You can also redeem your gift card at checkout using this claim code: NE7N-TUD6NV-GUAB We hope to see you again soon, Amazon.com Once applied to your Amazon account, the entire amount will be added to you= r gift card balance. Your gift card balance can't be transferred to other a= ccounts, used to buy other gift cards, or, except as required by law, redee= med for cash. Your gift card balance will be applied automatically to eligible orders dur= ing the checkout process and when using 1-Click. If you don=E2=80=99t want = to use your gift card balance on your order, you can unselect it as a payme= nt method in checkout.=20 If you experience any issues using your gift card, you can reference your g= ift card by providing the following information to Customer Service: Order Number: 234343433433";
preg_match_all("/(?<=\bclaim code: )\S+/", $message, $matches);
print_r($matches[0][0]);

Это печатает:

NE7N-TUD6NV-GUAB

Основная проблема в вашем текущем подходе - сам шаблон регулярных выражений. \s* соответствует нулю или более пробельных символов, вы должны использовать вместо \S*, как я использовал выше.

0 голосов
/ 26 января 2020

Вы можете достичь этой цели, используя позитивный взгляд позади . Я бы предложил использовать preg_match, если у вас не более одного кода претензии. Потому что preg_match_all() больше потребителя памяти, чем preg_match(). Для вашего решения, проверьте следующий код:

$message = "Hurray! You've received a $100 Amazon Gift Card. Hope you enjoy this Amazon Gift Card! What's next? Apply the gift card to your Amazon account:=20 https://www.amazon.com/g/ Don't have an Amazon account? Sign up to redeem: www.amazon.com You can also redeem your gift card at checkout using this claim code: NE7N-TUD6NV-GUAB We hope to see you again soon, Amazon.com Once applied to your Amazon account, the entire amount will be added to you= r gift card balance. Your gift card balance can't be transferred to other a= ccounts, used to buy other gift cards, or, except as required by law, redee= med for cash. Your gift card balance will be applied automatically to eligible orders dur= ing the checkout process and when using 1-Click. If you don=E2=80=99t want = to use your gift card balance on your order, you can unselect it as a payme= nt method in checkout.=20 If you experience any issues using your gift card, you can reference your g= ift card by providing the following information to Customer Service: Order Number: 234343433433";

preg_match('/(?<=\bclaim\scode\b:\s)\S+/', $message, $matches);
echo $matches[0]; // NE7N-TUD6NV-GUAB

Положительный Lookbehind:

Гарантирует, что данный шаблон будет соответствовать, заканчивая в текущей позиции в выражении. Узор должен иметь фиксированную ширину. Не использует никаких символов.

Синтаксис:

(?<=...)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...