Regex - picking certain values - PHP

Asked

Viewed 108 times

3

I’m in doubt, I tried to read several articles on regular expressions, but it still didn’t fit in my mind, I get 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 __. i.e., it is more or less as if each __ is a comma and the .. is equal. I used that trick

$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 direct, that could separate in the regular expression the elements, and if possible take only oidN, ie oid1.. oid2... etc

  • I need to know, if the variable as well as the value can have any character.

2 answers

2

I believe the REGEX you need is this:

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

Whether 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 will be like this:

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

$vars = array();
foreach($match[1] as $k => $options){
    $vars[$options] = $match[2][$k];
}
  • 1

    I used your technique, seems to be a little faster, thanks man

2


Now, if attributes are delimited by a __ and its values for .. 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 use regular expressions because, in this particular case, it is not pragmatic and is less explicit about what is to be achieved. Separating the string by snippets with explode and adjusting the pairs of (attribute=value) is more practical and less "foggy".

Here is an executable version of the code: https://3v4l.org/WapO5

  • I used the other user’s technique, but yours also works perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.