php从字符串中提取多个文本部分

时间:2016-12-14 13:28:04

标签: php string preg-match

我试图以下列方式提取文字:

$subname = "subarray({value=subarray({0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48}, EXCEL*48, 1)";            
preg_match('#\{(.*?)\}#',$subname, $match,  PREG_OFFSET_CAPTURE);
print_r($match[1][1]);
$matchs = substr( $subname, 0, $match[1][1]);
print_r($matchs);

我想从$ subname

获取以下文字
  1. 0.5,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 ,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48
  2. EXCEL
  3. * 48
  4. 我正在努力争取第二位(获得EXCEL字样)。我想知道是否有可能让preg_match给我剩下的字符串?

1 个答案:

答案 0 :(得分:1)

您可以使用

'#\{([\s\d.,]*)},\s*(\p{L}+)(\*\d+)#'

请参阅regex demo

详细

  • \{ - {
  • ([\s\d.,]*) - 第1组捕获0 +空格,数字,逗号和点
  • } - 文字}
  • , - 逗号
  • \s* - 0+ whitespaces
  • (\p{L}+) - 第2组:一个或多个字母
  • (\*\d+) - 第3组:*和1+位数。

请参阅下面的PHP demo

$subname = "subarray({value=subarray({0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48}, EXCEL*48, 1)";            
$res = array();
if (preg_match('#\{([\s\d.,]*)},\s*(\p{L}+)(\*\d+)#',$subname, $match)) {
    $res = explode(", ", $match[1]);
    array_push($res, $match[2]);
    array_push($res, $match[3]);
}
print_r($res);