need help in regular expression namely:
This is how the script works fine:

function callbackFunction( $matches) { echo $matches[1]."\n"; echo $matches[2]."\n"; echo $matches[3]."\n"; } $pattern = '!\\[hide=([0-9,]+),user=(.+?)\\](.+?)\\[\\/hide\\]!is'; $subject = '[hide=3,user=test1,test2]rgqgefrefe[/hide]'; print_r(preg_replace_callback($pattern, 'callbackFunction', $subject, -1)); 

Conclusion

 3 test1,test2 rgqgefrefe 

if we remove the user in the subject, the code does not work

 $subject = '[hide=3]rgqgefrefe[/hide]'; 

I need the Hybrid to work with both [hide=цифра,user=логин] , as well as separately as [hide=1] and [hide=login1,login2] and what the result would be like

 1 user1,user2 rgqgefrefe 
  • To begin with, specify what kind of string you are looking for and what do you want to do with it? - Anton Shchyrov
  • I need the hde to work with both [hide = digit, user = login], as well as separately as [hide = 1] and [user = login1, login2] and what the result would be like / * result: 1 user1 , user2 rgqgefrefe * / - GDRest
  • And for [user=login1,login2] closing tag should be [/user] ? - Anton Shchyrov
  • Well, look, let's say a forum for the forum, [hide = message digit, user = login or login] text [/ hide] and if only login is allowed then [hide = test] text [/ hide] - GDRest

1 answer 1

Since you have this part user=test1,test2 not required, it would be better to use named submasks. The template will look like this:

 \[hide=(?<hide>.+?)(?:,\s?user=(?<user>.+))?](?<text>.+?)\[/hide] 

It is better to write the code using preg_match_all ():

 $str = '[hide=3, user=текст1, текст2]текст[/hide]'; //$str = '[hide=hide]текст[/hide]'; // Этот вариант тоже рабочий $patt = '~\[hide=(?<hide>.+?)(?:,\s?user=(?<user>.+))?](?<text>.+?)\[/hide]~'; preg_match_all($patt, $str, $arr); var_dump($arr['hide'], $arr['user'], $arr['text']); 
  • one
    NULL NULL array (6) {[0] => string (1) "i" [1] => string (6) "= 3, us" [2] => string (2) "= t" [3] => string (5) "t1, t" [4] => string (14) "t2] text [" [5] => string (1) "i"} here is the answer from this function, something is wrong GDRest
  • @GDRest look here - DROP
  • and if individually not in the dump? echo var_dump ($ arr ['hide']); // NULL // echo $ arr ['user']; // echo $ arr ['text']; something doesn't come out - GDRest
  • @GDRest is the same arrays, so no var_dump($arr['hide']); is needed var_dump($arr['hide']); , and here it is: echo $arr['hide'][0], $arr['user'][0], $arr['text'][0]; . Well, or in a loop, print each array if necessary. The task is in finding and receiving the necessary substrings, and not in their processing. - DROP
  • sandbox.onlinephpfunctions.com/code/… and if we allow it in this form, how will the function work correctly? - GDRest pm