Home > OS >  PHP - how to extract all the substrings that are wrapped by certain characters
PHP - how to extract all the substrings that are wrapped by certain characters

Time:06-29

I have a string $url = "https://example.com/aff_lsr?transaction_id={{transactionId}}&adv_sub2={{sub_uuid}}&adv_sub3={{promoCode}}"

I want to extract the substrings that are wrapped by {{ and }}. How can I do that in PHP?

CodePudding user response:

To extract values between {{ and }} you can use regex

$url = "https://example.com/aff_lsr?transaction_id={{transactionId}}&adv_sub2={{sub_uuid}}&adv_sub3={{promoCode}}";
preg_match_all('/\{{(.*?)\}}/', $url, $matches);
echo '<pre>' . var_export($matches, true) . '</pre>';  // result

however, it would be easier to get query parameters by parsing url.

$url = 'https://example.com/aff_lsr?transaction_id={{transactionId}}&adv_sub2={{sub_uuid}}&adv_sub3={{promoCode}}';
$url_components = parse_url($url);
parse_str($url_components['query'], $params);
echo '<pre>' . var_export($matches, true) . '</pre>'; // result
  • Related