Regex - taking certain values - PHP

3

I'm in doubt, tried to read several articles about regular expressions, but it still did not fit my mind, I'm confused. I have a certain string

vid..0002-3f3c-458c-8000__vpid..e29ac000-8020-395e__caid..8ff77872-a0cb-4d7c-a36c0bd6__rt..D__lid..a1b926-17da-45b8-8bfc-32464ba72cdd__oid1..7ef55782-6c4b-414e-b7b9-faa2d55b32e1__oid2..a2292a00-31ce-4366-b6c6-72a0204b38be__var1..%7Bname%7D__var2..MLPUBID__var3..%7Bheadline%7D__var4..%7Bimage%7D__var5..%7Badid%7D__var6..%7Bad%7D__var7..%7Bage%7D__rd..__aid..__sid..

In the middle of this string, each attribute is separated by __. that is to say, it is more or less as if each __ were a comma and the ... was equal. I used this gambiarra

$str = str_replace("..", "=", $_REQUEST['voluumdata']);
$str = str_replace("__", ", ", $str);
preg_match_all("/([^,= ]+)=([^,= ]+)/", $str, $r); 
$voluum = array_combine($r[1], $r[2]);

I would like something more straightforward, that I could separate the regular elements into the regular expression, and if possible I would just pick the oidN, ie oid1 .. oid2 ... etc

    
asked by anonymous 07.09.2015 / 16:09

2 answers

2

Now, if attributes are delimited by a __ and their values by .. it is very simple to perform this extraction task:

<?php
# É sua string principal, da qual se quer extrair
$str = 'vid..0002-3f3c-458c-8000__vpid..e29ac000-802 ...';
$split = explode('__', $str);
# um array (chave => valor) representando os atributos
 $results = array_map(function($e){
    return explode('..', $e);
}, $split);


print_r($results);

It is not necessary to make use of regular expressions because, in this specific case, it is not pragmatic in addition to being less explicit about what you want to get. Separating the string by excerpts and adjusting the pairs of (attribute = value) is more practical and less "nebulous."

Here is an executable version of the code: link

    
07.09.2015 / 16:24
2

I think the REGEX you need is this:

([^\.]+)\.{2}([^_]*)_{0,2}

Be working on Regex101

Explanation

([^\.]+) = Grupo 1, vai pegar qualquer coisa que não seja '.', no minimo 1 vez  
\.{2} = literal '.', ira capturar '.' duas vezes
([^_]*) = Grupo 2, var capturar qualquer coisa que não seja _, 0 ou infinitas vezes
__{0,2} = captura do carácter _ no final para suprir e não ser capturado pela var.

PHP

To recover your values in PHP it will look like this:

preg_match_all("/([^\.]+)\.{2}([^_]*)_{0,2}/", $str, $match);

$vars = array();
foreach($match[1] as $k => $options){
    $vars[$options] = $match[2][$k];
}
    
07.09.2015 / 16:23