Stanislav Belichenko Stanislav Belichenko - 2 years ago 78
PHP Question

Geting two matches in a string using a regular expression

My string:

fields[name_1]


I want to get
fields
and
name_1
using regex.

I'm know about
preg_match_all()
, but I'm not friends with regular expressions.

Answer Source

This can be used for direct match:

$string = 'fields[name_1]';

preg_match('/(.+)\[(.+)\]/', $string, $matches);

print_r($matches);

You get:

Array
(
    [0] => fields[name_1]
    [1] => fields
    [2] => name_1
)

So, $matches[1] and $matches[2] are what you needed.


Still I am unclear about your exact need!


Here are the explanation for the Regex:

  1. https://regex101.com/r/PcJzQL/3
  2. http://www.phpliveregex.com/
  3. https://www.functions-online.com/preg_match.html
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download