Как написать регулярное выражение, которое удаляет все после $ _POST ['some_string'] - PullRequest
0 голосов
/ 18 июня 2019

У меня есть следующая строка:

string = '$_POST["a_string_of_unspecified_length"][4]input&set1';

Как написать регулярное выражение, которое будет возвращать только $_POST["a_string_of_unspecified-length"] и отбросить все после первого набора скобок

$string_afer_regex = '$_POST["a_string_of_unspecified_length"]'

1 Ответ

2 голосов
/ 18 июня 2019

С регулярным выражением ^\$_POST\[[^]]+\]

$str = '$_POST["a_string_of_unspecified_length"][4]input&set1';
preg_match('~^\$_POST\[[^]]+\]~', $str, $matches);
print_R($matches);
// $_POST["a_string_of_unspecified_length"]

^     - beginning of string
\$    - escaped dollar sign
_POST - normal characters, just part of string
\[    - escaped '['
[^]]+ - everything till ']', + means 'more than 1 character'
\]    - escaped '['
the rest doesn't care us, there can be whatever

Без регулярного выражения, если необходимо

$str = '$_POST["a_string_of_unspecified_length"][4]input&set1';
echo substr($str, 0, strpos($str, ']') + 1);
// $_POST["a_string_of_unspecified_length"]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...