mercredi 6 mai 2015

Error parsing regex pattern in php

I want to split a string such as the following (by a divider like '~@@' (and only that)):

to=enquiry@test.com~@@subject=test~@@text=this is body/text~@@date=date/this isn't camptured after the slash

into an array containing e.g.:

to => enquiry@test.com
subject => test
text => this is body/text
date => date 

I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:

        //Split the string in the url of $text at every ~@@
        $regexp = "/(?:|(?<=~@@))(.*?=.*?)(?:~@@|$|\/(?!.*~@@))/";
        preg_match_all($regexp, $text, $a); 
        //$a[1] is an array containing var1=content1 var2=content2 etc;

        //Now create an array in the form [var1] = content, [var2] = content2
        foreach($a[1] as $key => $value) {
            //Get the two groups either side of the equals sign
            $regexp = "/([^\/~@@,= ]+)=([^~@@,= ]+)/";
            preg_match_all($regexp, $value, $r); 

            //Assign to array key = value
            $val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
        }

        print_r($val);

My queries are that: 1. It doesn't seem to capture more than 3 different sets of parameters 2. It is breaking on the @ symbol and so not capturing email addresses. 3. I am doing multiple different regex searches where I suspect I would be able to do one.

Any help would be really appreciated.

Thanks

Aucun commentaire:

Enregistrer un commentaire