Sudhanshu Gupta
Sudhanshu Gupta

Reputation: 2315

Preg_match_all regex expression is not fully correct

I was using Preg_match_all in php and written a regex which was working fine as expected Regex : '/"([0-9A-z ]*)("|$)/' String to be searched are :

["100"]
["100","200"]
["100","200","300"]

Array from preg

array (
  0 => 
  array (
    0 => '"100"',
    1 => '"200"',
    2 => '"300"',
  ),
  1 => 
  array (
    0 => '100',
    1 => '200',
    2 => '300',
  ),
  2 => 
  array (
    0 => '"',
    1 => '"',
    2 => '"',
  ),
)

So i was getting data from array 1

But now we are also getting data like :

[100]
[100,200]

and i want a single regex for both the types but unable to do so. i tried to write

/"([0-9A-z ]*)("|$)|[0-9]*/

But it was not giving what i expected. Can anyone help me with this

One more thing is needed :- When i was using regex Lets says the data is like :-

["",""]

Array i was getting :-

array (
  0 => 
  array (
    0 => '""',
    1 => '""',
  ),
  1 => 
  array (
    0 => '',
    1 => '',
  ),
  2 => 
  array (
    0 => '"',
    1 => '"',
  ),
)

So from this i was taking array 1 , so getting empty But all the regex i am getting is giving me :-

array (
  0 => 
  array (
  ),
)

Can a regex be like which gives me the with all the following conditions.

Upvotes: 2

Views: 67

Answers (3)

Sudhanshu Gupta
Sudhanshu Gupta

Reputation: 2315

You can simply decode it the way you want with an in build function PHP provides.

Use json_decode

You can see the implementation here :- https://ideone.com/IFEe6p

This function will work for everything except [] [,,] These type of strings should be handled separately.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

A non-regex way

You can leverage eval method:

$string = '["100","200","300"]';
// $string = '[100,200, 300]';
eval('$array = array('.$string.');');
print_r($array);

See IDEONE demo

Regex way

There can be 2 approaches depending on your input.

The hardest way is to make sure we are inside [...]:

(?:\[|(?<!^)\G)"?,?([0-9 ]+)"?,?(?=[^]]*\])

See demo

A more efficient regex can be used if your input is already pre-filtered and you only get strings as you have shown above:

[0-9 ]+(?="?|,)

See demo

Upvotes: 1

splash58
splash58

Reputation: 26153

Maybe in the case the simple expression helps you

/([\d]+)/g

DEMO

Upvotes: 0

Related Questions