function recipe_plaintext_import in Recipe 6
Same name and namespace in other branches
- 7.2 modules/recipe_plaintext.module \recipe_plaintext_import()
- 7 includes/recipe_plaintext.module \recipe_plaintext_import()
Parsing instance for plain text recipes
1 string reference to 'recipe_plaintext_import'
- recipe_plaintext_recipeio in plugins/
recipe_plaintext.module - Implementation of hook_recipeio($type).
File
- plugins/
recipe_plaintext.module, line 55
Code
function recipe_plaintext_import($text) {
// region constants
define('TITLE', 0);
define('INGREDIENTS', 1);
define('DIRECTIONS', 2);
$recipe = array();
// init ingredients here
$recipe['ingredients'] = array();
$region = TITLE;
foreach (split("\n", $text) as $line) {
$line = trim($line);
if ($region < DIRECTIONS && $line == '') {
$region++;
continue;
}
if ($region == TITLE) {
$recipe['title'] = $line;
}
elseif ($region == INGREDIENTS) {
// Replace a decimal quantity with a fractional one. Needs to be done before ' ' to '-' below.
$line = preg_replace_callback('/^(\\d+\\.\\d+)/', 'decimal_to_fraction_callback', $line);
// Replace a space separated fraction with a '-' to normalize the input string.
$line = preg_replace('/^(\\d+)[ \\-](\\d+)[\\/](\\d+)/', '${1}-${2}/${3}', $line);
// 1 cup flour
if (preg_match('/^([0-9\\-\\.\\/]+) +([A-Za-z\\.]+) +(.*)/', $line, $matches)) {
$i = array();
$i['quantity'] = $matches[1];
$i['unit_name'] = $matches[2];
$i['ingredient_name'] = $matches[3];
// FALSE if no-match
$i['unit_obj'] = recipe_unit_fuzzymatch($i['unit_name']);
if ($i['unit_obj'] == FALSE) {
$i['unit_name'] = 'Unit';
$i['unit_obj'] = recipe_unit_fuzzymatch($i['unit_name']);
drupal_set_message(t('Could not find the ingredient units in "%s"', array(
'%s' => $line,
)), 'warning');
}
// FALSE if no-match
$i['ingred_obj'] = recipe_ingredient_match($i['ingredient_name']);
$recipe['ingredients'][] = $i;
}
elseif (preg_match('/^([0-9\\-\\.\\/]+) +(.*)/', $line, $matches)) {
$i = array();
$i['quantity'] = $matches[1];
$i['unit_name'] = 'Unit';
$i['ingredient_name'] = $matches[2];
// FALSE if no-match
$i['unit_obj'] = recipe_unit_fuzzymatch($i['unit_name']);
// FALSE if no-match
$i['ingred_obj'] = recipe_ingredient_match($i['ingredient_name']);
$recipe['ingredients'][] = $i;
}
else {
$i = array();
$i['quantity'] = 0;
$i['unit_name'] = 'Unit';
$i['ingredient_name'] = "failed: " . $line;
$i['unit_obj'] = FALSE;
$i['ingred_obj'] = FALSE;
$recipe['ingredients'][] = $i;
}
}
elseif ($region == DIRECTIONS) {
$recipe['instructions'] .= $line . "\n";
}
}
return $recipe;
}