-2

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.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • 1
    Such a banal question around Regular Expressions, gets some up-voted answers. Something's wrong. – revo Jul 27 '17 at 09:51
  • 3
    https://stackoverflow.com/questions/8935717/php-regular-expression-string-from-inside-brackets – revo Jul 27 '17 at 09:54

2 Answers2

3

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
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • thx. You were the first, so your answer will be marked as true. – Stanislav Belichenko Jul 27 '17 at 09:48
  • 1
    You might want to use `+` instead of `*`. Currently your regex will match a simple `[]` with both groups empty. [Compare here](https://regex101.com/r/PcJzQL/2). I know you are not using global flag, but if there were more matches in string it would be safer to use the plus sign for quantifier. – Asunez Jul 27 '17 at 10:10
  • @StanislavBelichenko - you might want to consider my comment above. – Asunez Jul 27 '17 at 10:12
  • @Asunez Thanks modified! – Thamilhan Jul 27 '17 at 10:20
2

THere are uncounted examples for this alone here on SO. A simple search would have shown you what you need. Anyway, to get you going:

<?php
$subject = 'fields[name_1]';
preg_match('/^(.+)\[(.+)]$/', $subject, $tokens);
print_r($tokens);

The output of that obviously is:

Array
(
    [0] => fields[name_1]
    [1] => fields
    [2] => name_1
)
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • thx. My English is too bad for right search this exaples, sorry. – Stanislav Belichenko Jul 27 '17 at 09:45
  • 1
    @StanislavBelichenko Then start reading the official documentation of the php functions you want to use. They are of good quality, come with helpful examples and are translated in many languages: http://php.net/manual/en/function.preg-match.php – arkascha Jul 27 '17 at 09:47
  • You are right, I did not think at all that there could be a similar example. – Stanislav Belichenko Jul 27 '17 at 09:49
  • 1
    If you knew that there are thousands of examples around this topic on SO then wouldn't it be better if you voted this question to be closed as a duplicate instead of posting an answer? – revo Jul 27 '17 at 09:56