php - Best way to extract data from a string -
i looking efficient , clean way extract data string , organize array of information. i'm building tool converts pasted memo information more readable format.
at moment receive memos new employees this:
name: john smith
service: ict
manager: john turner
post title: support officer
i want able put of information array fetched textarea post , display on page in nicer format below:
full name: john smith
service area: ict
line manager: john turner
job title: support officer
i aware use functions explode() wanted see if there better ways this?
i want store of information in array easy echo onto webpage once has been posted server.
$newemployee['name'] = "john smith"; $newemployee['service'] = "ict"; $newemployee['manager'] = "john turner"; $newemployee['post_title'] = "it support officer";
if has suggestions great.
assuming have no control on format of input, , without sanitising input in way, believe suitable way achieving using functions explode() have described:
$newuser = []; $input = "name: john smith service: ict manager: john turner post title: support officer"; $lines = array_filter(explode("\n", $input)); foreach ($lines $line) { $parts = explode(": ", $line); $newuser[ucfirst(strtolower(str_replace(" ", "_", $parts[0])))] = $parts[1]; }
edit
have changed array indexes reflect formatting have described.
as actual values, better off storing of values in same form (i.e. lowercase) , formatting them accordingly when printing them on screen. allows compare values without needing know format of each string - meaning can detect things 'ict' acronym , have uppercase, whereas 'service' may not acronym , prefer capitalised.
Comments
Post a Comment