Skip to content
Advertisement

Regex pluck parts too, not whole string

This is my input content:

$input = 'Hi there,

You recently ... {{client.events.add_to_cart.product_name}}, ...

..

Also

...

{{client.events.purchase.product_name}}
';

and this is regex example:

$regex = "'(?:{{client.events.)w+(?:.)w+(?:}})'";

preg_match_all($regex, $input, $matches);

This is the $matches content:

array:1 [
  0 => array:2 [
    0 => "{{client.events.add_to_cart.product_name}}"
    1 => "{{client.events.purchase.product_name}}"
  ]
]

Not bad, but I’d like somehow to pick “add_to_cart” and “product_name” as well. I can do it with explode() function, but wonder if there is a way to do this by regex only once.

Also, I wonder if it is possible to have ‘target’ these too:

  • {{client.events.add_to_cart.product_name}}
  • {{client.events.add_to_cart.0.product_name}}
  • {{client.events.add_to_cart.1.product_name}}

with and without numbers. And also knowing the number.

Thanks.

Advertisement

Answer

This will do it: ({{client.events.(?:purchase|(add_to_cart))(?:.d)?.(.*)}})

See: https://regex101.com/r/EKAJsG/1

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement