sumion
sumion

Reputation: 147

Parse substring from a string that starts with specific word

I have a mutli-line string $comment, which looks like:

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

I want to convert it into six different strings so that after the conversion it should look like: $description = 'some description', $features = 'some features' and so on. How can I achieve that?

I have tried explode, but it's not working for me. I'm a beginner in PHP and would appreciate any help.

Upvotes: 0

Views: 124

Answers (2)

A. Iglesias
A. Iglesias

Reputation: 2675

You can use explode twice, one with the @ separator to get the fields and then with the : separator to get each field content...

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

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

You can simplify it a little bit using the array_map function to get the field content...

$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];
....

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short solution using preg_replace, explode and list functions:

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

The output (for all variables created):

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"

Upvotes: 0

Related Questions