Skip to content
Advertisement

regex php separate an exact word from string in diffrent groups

i have tried all i know but still can’t figure out how to resolve this problem :

i have a string ex :

  • "--included-- in selling price: 5 % vat usd 10.00 packaging fees 2 % notifying fees"
  • "--not included-- in selling price: us$ 35.00 express fees 2 % notifying fees"

i want to know if the taxes are “included” or “excluded” and if the fees are “%” or “currency” the problem is it doesn’t detect the currency “usd” while it’s attached to the taxe name “vat usd”

how can i separate the currency from the name of the taxe in different groups.

here is what i did

JavaScript

and here is what i got

JavaScript

and here is what i want

JavaScript

Advertisement

Answer

Here is the solution:

JavaScript

See the PHP demo.

Notes:

The first regex extracts each match you need to parse. See the first regex demo. It means:

  • (--(?:(?:not )?in|ex)cluded--) – Group 1: a shorter version of (--excluded--|--included--|--not included--): --excluded--, --included-- or --not included--
  • (?:s+([a-zA-Z ]+))? – an optional sequence: 1+ whitespaces and then Group 2: 1+ ASCII letters or spaces
  • :+ – 1 or more colons
  • s* – 0+ whitespaces
  • ((?:(?!--(?:(?:not )?in|ex)cluded--).)*) – Group 3: any char, 0+ occurrences, as many as possible, not starting any of the three char sequences: --excluded--, --included--, --not included--

Then, the Group 3 value needs to be further parsed to grab all the details. The second regex is used here to match

  • (?:(b(?:usd|aed|mad|usd)b|B€|bus$)s*)? – an optional occurrence of
    • (b(?:usd|aed|mad|usd)b|B€|bus$) – Group 1:
      • b(?:usd|aed|mad|usd)busd, aed, mad or usd as whole words
      • B€ not preceded with a word char
      • bus$us$ not preceded with a word char
    • s* – 0+ whitespaces
  • d+
  • (?:.d+)? – an optional sequence of . and 1+ digits
  • (?:(?!(?1))D)* – any non-digit char, 0 or more occurrences, as many as possible, not starting the same pattern as in Group 1
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement