How to fix this regular expression so that it does not return those characters that are specified at the end (characters / , * and пробел )

Here is the code:

 preg_match_all("/[\/\*\s]*(.+)[\/\*\s]*/i", $str, $matches); var_dump($matches); 

If you pass the string */* str __#@33$*/%^& //* to this regular expression, you should return str __#@33$*/%^& , but return str __#@33$*/%^& //* .

These 4 //* symbols at the end should have disappeared, since the rule states:

/[/\*\s (). [/ \ * * s] * / i

I understand that .+ Captures everything, without checking that there should not be at the end //*

How to fix this expression? Also, these characters //* should not be ONLY at the end, they can be present in .+ , Therefore variants of the type [^\/\*\s]+ immediately disappear.

Also, if you make an expression like / /[\/\*\s]*(.+)[\/\*\s]+/i () str __#@33$*/%^& // /[\/\*\s]*(.+)[\/\*\s]+/i , the result will already be without an asterisk at the end: str __#@33$*/%^& // .

It turns out you can do it like this: / /[\/\*\s]*(.+)[\/\*\s]{4}/i / /[\/\*\s]*(.+)[\/\*\s]{4}/i str __#@33$*/%^& /[\/\*\s]*(.+)[\/\*\s]{4}/i and the result will be as needed: str __#@33$*/%^& , but the characters on the end may not be 4, but more or less, or it may not be at all.

Maybe something is connected with lazy and greedy checks? I do not understand anything.

  • .+ captures everything that can capture. This is called greedy capture. To reduce greed, you must use a question mark. .+? then it will only capture the first character that falls under the following expression - Mike
  • @ user269067 I replied to you yesterday in this topic: ru.stackoverflow.com/questions/724877/… - Edward
  • @Edward it doesn’t work - user269067
  • And plus it does not capture the characters /* in .+ - user269067
  • @Mike then the result will be like this: goo.gl/pQbnQu (even if all this is combined into a single string, then spaces are still not captured, if there is a string like *// str1 str 2/** ) - user269067

1 answer 1

It seems to be what you need:

 <?php $str = '*/* str__#@33$*/%^&* //*'; $patt = '~(?<=\s)[\S\s]+(?=\s)~i'; preg_match_all($patt, $str , $a); echo '<pre>'; var_dump($a); echo '</pre>'; //str__#@33$*/%^&* 
  • @ user269067 To understand the regulars well, read Jeffrey Friddle's Regular Expressions. - Edward
  • @ user269067 you changed your nn, so I corrected the template to reflect the changes. - Edward