我有类似的东西:
$ string1 ="狗狐狸[猫]"
我需要[]即cat中的内容
另一个问题:如果你熟悉一种语言的正则表达式,那么它也适用于其他语言吗?
$matches = array();
$matchcount = preg_match('/\[([^\]]*)\]/', $string1, $matches);
$item_inside_brackets = $matches[1];
Run Code Online (Sandbox Code Playgroud)
如果您想在同一个字符串中匹配多个括号内的术语,您需要查看preg_match_all而不是仅仅preg_match.
是的,正则表达式是一种相当的跨语言标准(不同语言中可用的功能有一些变化,偶尔会出现语法差异,但大多数情况下它们都是相同的).
上述正则表达式的解释:
/ # beginning of regex delimiter
\[ # literal left bracket (normally [ is a special character)
( # start capture group - isolate the text we actually want to extract
[^\]]* # match any number of non-] characters
) # end capture group
\] # literal right bracket
/ # end of regex delimiter
Run Code Online (Sandbox Code Playgroud)
$matches数组的内容是根据[0]中匹配的文本(包括括号)的全部设置,然后是[1]及以上匹配的每个捕获组的内容(第一个捕获组的内容)在[1],第二[2]等).