如何从数组中提取自定义文本


How to Extract custom Text from Array

我有这样的文字

   "From: [your-name] <[your-email]>
    Subject: [your-subject]
    Message Body: [your-message]"

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

:

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

如何使用preg_match_all()做到这一点

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

$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" }
$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);