从以特定单词开头的字符串中解析子字符串

Parse substring from a string that starts with specific word

我有一个多行字符串 $comment,它看起来像:

@Description: some description.
@Feature/UseCase: some features.
@InputParameter: some input param.
@ChangedParameter: some changed param.
@NewOutputParameter: some output param.
@Comments/Note: some notes.

我想将它转换成六个不同的字符串,这样转换后它应该看起来像:$description = 'some description'$features = 'some features' 等等。我怎样才能做到这一点?

我试过 explode,但它对我不起作用。我是 PHP 的初学者,非常感谢任何帮助。

您可以使用 explode 两次,一次使用 @ 分隔符获取字段,然后使用 : 分隔符获取每个字段内容...

$fields = explode("@",$comment);

$description = trim(explode(":",$fields[1])[1]);
$features = trim(explode(":",$fields[2])[1]);
$inputparameter = trim(explode(":",$fields[3])[1]);
....

您可以使用 array_map 函数稍微简化一下以获取字段内容...

$fields = array_slice(explode("@",$comment),1);
$fieldcontents = array_map(function($v) { return trim(explode(":",$v)[1]); }, $fields);

$description = $fieldcontents[0];
$features = $fieldcontents[1];
$inputparameter = $fieldcontents[2];
....

使用 preg_replaceexplodelist 函数的简短解决方案:

$comment = '
    @Description: some description.
    @Feature/UseCase: some features.
    @InputParameter: some input param.
    @ChangedParameter: some changed param.
    @NewOutputParameter: some output param.
    @Comments/Note: some notes.';

list($description, $feature, $input_param, $changed_param, $new_param, $note) = 
    explode('.', preg_replace('/\s*@[^:]+:\s*([^.]+.)/', '', $comment));

var_dump($description, $feature, $input_param, $changed_param, $new_param, $note);

输出(对于创建的所有变量):

string(16) "some description"
string(13) "some features"
string(16) "some input param"
string(18) "some changed param"
string(17) "some output param"
string(10) "some notes"