我有以下字符串: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 回答
Helenr
TA贡献1780条经验 获得超4个赞
使用正则表达式 ^\$_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"]
- 1 回答
- 0 关注
- 134 浏览
添加回答
举报
0/150
提交
取消