Let's say I have a string like
"Student - John Doe ate apples"
"Student - Bob ate oranges"
I know this sentence consists of: ":type - :who ate :noun
Is there a way to get an array of actions, utilising both strings such as :
$arr = [
"type" => "Student",
"who" => "John Doe",
"noun" => "apples"
];
$arr2 = [
"type" => "Student"
"who" => "Bob",
"noun" => "oranges"
];
What is the way to achieve this in php?
- I couldn't think of any way to achieve it so I can't put any code chunks.
- Probably I couldn't even name the question correctly, I'd appreciate a better name if you have any idea
You can also split the string on the patterns of characters that divide the different parts.
$result = array_combine(['type', 'who', 'noun'], preg_split('/ - | ate /', $example));
This should work reliably, assuming there's not a Bob ate who ate an ate or something like that.
This can actually be done without any regex if you really do have the strict rules given in your updated question. First split by the dash to get the type, then split the rest by "ate" to get the person and the noun.
$strings = array("Student - John Doe ate apples", "Student - Bob ate oranges");
$breakdown = array();
foreach($strings as $line)
{
$mainParts = explode("-", $line);
$type = trim($mainParts[0]);
$subPart = explode(" ate ", $mainParts[1]);
$who = trim($subPart[0]);
$noun = trim($subPart[1]);
$breakdown[] = array("type" => $type, "who" => $who, "noun" => $noun);
}
var_dump($breakdown);
You could use a regular expression with named groups. This assumes the input string is $str
:
preg_match("/^(?<type>\w+)\s+-\s+(?<who>\w+(?:\s+\w+)*)\s+ate\s+(?<noun>\w+)$/",
$str, $match);
This will set $match
to a bit more than needed, but you can just grab from it what you need:
[
0 => "Student - John Doe ate apples",
"type" => "Student",
1 => "Student",
"who" => "John Doe",
2 => "John Doe",
"noun" => "apples",
3 => "apples"
]