如何从Array中提取自定义文本

时间:2015-09-18 10:02:26

标签: php arrays

我有像

这样的文字
   "From: [your-name] <[your-email]>
    Subject: [your-subject]
    Message Body: [your-message]"

我想提取[ ]所包含的字符串。

像:

your-name
your-email
your-subject
your-message

如何使用preg_match_all()完成此操作?

2 个答案:

答案 0 :(得分:1)

从输入中获取所有匹配项:

$text = 'From: [your-name] <[your-email]> Subject: [your-subject] Message Body: [your-message]';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
var_dump($matches[0]);

将输出:

{ [0]=> string(11) "[your-name]" [1]=> string(12) "[your-email]" [2]=> string(14) "[your-subject]" [3]=> string(14) "[your-message]" }

如果您不想包含括号:

$text = 'From: [your-name] <[your-email]> Subject: [your-subject] Message Body: [your-message]';
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
var_dump($matches[1]);

将输出:

{ [0]=> string(9) "your-name" [1]=> string(10) "your-email" [2]=> string(12) "your-subject" [3]=> string(12) "your-message" }

答案 1 :(得分:0)

$text = 'From: [your-name] <[your-email]> Subject: [your-subject] Message Body: [your-message]';

// the pattern is very simple in your case, because you want to get the 
// content that is enclosed inside square brackets []
// \s means any whitespace character, where \S means any non whitespace character
$pattern = '/\[[\s\S]+?\]/';

//the created $matches variable is an array containing all the matched data
preg_match_all($pattern,$text,$matches);


// print out the matches array 
print_r($matches);