PHP提取字符前和字符后的字符串


PHP extract string before character and after character

我正在尝试创建一个验证类,但我需要获取选项,并将它们放入'['之后和']'之前的数组中。例如:

$dropdown = 'required|valid_option[general,recruitment,activities]';

然后我有这样的东西:

if(strops($str, '[')) {
   // this string contains options so grab them before ] and after [
}

我需要获取常规、招募和活动,然后我知道如何使用explode()将它们拆分,然后用array_push或类似的东西将它们放入数组中,但我真的需要弄清楚如何在[和之前]以某种方式获取字符串。我想不通。我猜它使用了某种preg_match

如有任何帮助,我们将不胜感激。

编辑:你是对的,很抱歉忘记澄清了。我将$rules作为包含(required,valid_option[options here])。。。其中的每一个都在|上分解,所以$rule包含'valid_option[option,option,option]'——我试图使用<,那个字符串在那里。

我想有人回答了如何获取选项,现在我该如何获取"有效选项"部分?我猜是这样的:

substr($rule, 0, $pos1)

您可以

preg_match_all("~(.*)'[(.*?)']~", $valid_options, $matches);

$matches将是正则表达式匹配的数组。

阵列将看起来像:

array
  0 => string 'valid_option[general,test,test2,recruitment,activities]'
  1 => string 'valid_option'
  2 => string 'general,test,test2,recruitment,activities'

怎么样

$pos1 = strpos($dropdown, '[');
$pos2 = strpos($dropdown, ']');
$options = substr($dropdown, $pos1, $pos2 - $pos1); 

至于方括号之前的零件,它将是substr($dropdown, 0, $pos1 - 1);,然后在|上爆炸

编辑:然后在","和|上分解$options,正如您在第一个位置提到的那样。