我有一个多行字符串$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的初学者,非常感谢任何帮助。
答案 0 :(得分:1)
您可以使用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];
....
答案 1 :(得分:0)
使用preg_replace
,explode
和list
函数的简短解决方案:
$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*([^.]+.)/', '$1', $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"