I am trying to arrange a large amount of content into an array based off of a series of array keys. All content after a key needs to be captured and associated with the the key until the next key is hit and the process stars all over.
Example content:
Frank
this is some text
this is some more text
this is additional text
Mary
omg some text went here
lawls this text is so silly
ipsum text went here
a fourth line of text goes here
George
a single line of text
Bob
some text with special characters: †
Example Array that I want to compared to the above string
array (
[0] => 'Mary',
[1] => 'George',
[2] => 'Bob',
[3] => 'Frank',
)
This is my desired final result:
array (
['Mary'] => '
this is some text
this is some more text
this is additional text
',
['George'] => '
omg some text went here
lawls this text is so silly
ipsum text went here
a fourth line of text goes here
',
['Bob'] => '
a single line of text
',
['Frank'] => '
some text with special characters: †
',
)
I've tried the markup below and it kind of works:
It's great that it doesn't depend on an array; but it's not very clean or accurate. The keys are not always wrapped in the same html and the below example is trying to be a catch-all. I'm looking for a way that I can ignore html wrappers like the example above.
// Split content into arrays by user
$results = preg_split("(</i>|</div>)", $content);
$results = preg_replace( '#<([^ >]+)[^>]*>([[:space:]]| )*</\1>#', '', $results );
// clean results and remove extra html
foreach($results as $key => $value) {
$key = strip_tags($key);
$value = strip_tags($value);
$results[$key] = $value; // strip html tags
if (strlen($value) > 0 && strlen(trim($value)) == 0) unset($results[$key]); // if array only has spaces in it, remove it
if (is_null($value) || $value == '' || empty($value)) unset($results[$key]); // if array is empty, remove it
}
I suppose in your $results
are clean strings you provided in the beginning of your question:
$names = []; // your names here
$lookup = []; // array for new results
$curr_key = ''; // current array key
foreach ($results as $item) {
if (in_array($item, $names)) {
/** we met a new name from `$names`
* change `$curr_key` and set empty array
* with key `$curr_key` in `$lookup`
*/
$curr_key = $item;
$lookup[$curr_key] = array();
} else {
// just add item to subarray under `$curr_key` key
$lookup[$curr_key][] = $item;
}
}
print_r($lookup);