将字符串分成 3 部分,中间以字母字符从 A 到 z 开始和结束


split string into 3 parts, the middle starts and ends with alphacharacter from A to z

$str="&%*&^h-e_l_lo*&^*&";

如何将其拆分为

$left="&%*&^";//until the first A-Za-z character
$right="*&^*&";//right after the last A-Za-z character
$middle = "h-e_l_lo";

我已经找到了找到$left的方法,但我怀疑这是最好的方法:

$curr_word = "&%*&^h-e_l_lo*&^*&";
preg_match('~[a-z]~i', $curr_word, $match, PREG_OFFSET_CAPTURE);
$left = substr($curr_word, 0,$match[0][1]);// &%*&^

您可以使用:

/([^a-zA-Z]*)(.*[a-zA-Z])(.*)/

解释

[^a-zA-Z]* 选择所有内容,直到到达字母

.*[a-zA-Z] 选择所有内容,直到到达最后一个字母

.* 选择字符串的其余部分

使用示例

$string = "&%*&^h-e_l_lo*&^*&";
preg_match('/([^a-zA-Z]*)(.*[a-zA-Z])(.*)/', $string, $matches);
echo $matches[1]; // Results in: &%*&^
echo $matches[2]; // Results in: h-e_l_lo
echo $matches[3]; // Results in: &^*&