简体   繁体   中英

preg_match from URL string

I have a string passed through a campaign source that looks like this:

/?source=SEARCH%20&utm_source=google&utm_medium=cpc&utm_term=<keyword/>&utm_content={creative}&utm_campaign=<campaign/>&cpao=111&cpca=<campaign/>&cpag=<group/>&kw=<mpl/>

when its present I need to cut this up and pass it through to our form handler so we can track our campaigns. I can check for it, hold its contents in a cookie and pass it throughout our site but i am having and issue using preg_match to cut this up and put it into variables so I can pass their values to the handler. I want the end product to look like:

$utm_source=google;
$utm_medium=cpc;
$utm_term=<keyword/>

there is no set number of characters, it could be Google, Bing etc, so i am trying to use preg_match to get the first part (utm_source) and stop past what I want (&) and so forth but I don't understand preg_match well enough to do this.

PHP should be parsing your query sting for you, into $_GET . Otherwise, PHP knows how to parse query strings. Don't use regular expressions or for this, use parse_str .

Input:

<?php

$str = "/?source=SEARCH%20&utm_source=google&utm_medium=cpc&utm_term=<keyword/>&utm_content={creative}&utm_campaign=<campaign/>&cpao=111&cpca=<campaign/>&cpag=<group/>&kw=<mpl/>";

$ar = array();
parse_str($str, $ar);
print_r($ar);

Output:

Array
(
    [/?source] => SEARCH
    [utm_source] => google
    [utm_medium] => cpc
    [utm_term] => <keyword/>
    [utm_content] => {creative}
    [utm_campaign] => <campaign/>
    [cpao] => 111
    [cpca] => <campaign/>
    [cpag] => <group/>
    [kw] => <mpl/>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM