这个任务最好避免使用正则表达式,只使用str_replace():
输入:
$str = 'button_reset,location_text,email_text';
输出为数组的代码:
var_export(explode(',',str_replace(['button_reset','location_text','email_text'],['reset','text','email'],$str)));
// array (
// 0 => 'reset',
// 1 => 'text',
// 2 => 'email',
// )
或者,如果您坚持,Regex (Demo Link):
/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/
正则表达式分解:
button_\K[^,]+ #Match one or more non-comma-characters after button_
| #or
,location_\K[^,]+ #Match one or more non-comma-characters after location_
| #or
,\K[^_]+(?=_text) #Match one or more non-underscore-characters that are
# immediately followed by _textafter button_
每个条件表达式中的\K 表示从这一点开始匹配,有效地消除了在这种情况下使用捕获组的需要。
当使用捕获组时,preg_match_all() 创建了多个子数组——一个填充了全字符串匹配,至少一个填充了捕获的值。
应尽可能使用\K,因为它可以将数组大小减少多达 50%。
代码:
$array=preg_match_all('/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/',$str,$out)?$out[0]:[];
var_export($array);
同样的输出:
array ( 0 => 'reset', 1 => 'text', 2 => 'email', )