当前位置: 动力学知识库 > 问答 > 编程问答 >

parsing - How would you parse this ingredient line?

问题描述:

I have a text area full of lines of ingredient; typically in a [quantity] [measurement] [ingredient] [additional] format. For example, a few ingredient lines might be:

1 tablespoon garlic, minced

1 cup bell pepper, chopped

I want to be able to identify each measurement and ingredient -- how would you process this? My line of thought was...

// loop thru line by line of textarea

// explode each line by the space thus line[0] would be 1, line[1] tablespoon, line[2] garlic... etc

Now here is my problem and I'm not sure what is efficient to do. Do I run each line[X] thru a db search for that measurement, ingredient, etc? But since "bell pepper" is separated by a space, I won't get a match.

// does line[1] appear in the measurements table?

// does line[2] appear in the ingredients table?

anyone else have any creative solutions?

网友答案:

Separate your data not by space but another delimiter. For example you could do:

$strRecipe = "1 | tablespoon | bell pepper |  minced";

And then you can use:

$recipe = explode("|",$strRecipe);

Now you can access each field by: $recipe[0], $recipe[1] ETC ETC

网友答案:

Try stripos() to locate substring instead of explode().

$mytext = "1 tablespoon garlic, minced 1 cup bell pepper, chopped"; # or any text
$keyword = "bell pepper"; # or any search term

if (stripos($mytext, $keyword) === false) {
  # not found
  ...
  }
else {
  # found
  ...
  }

References

  • stripos() - case-insensitive search
  • strpos() - case-sensitive search

You can use explode() (not recommended) but than also you should separate words in your search term and look for an occurrence of first keyword in array where next keyword follows in next element of array, etc. It's unnecessary complication.

分享给朋友:
您可能感兴趣的文章:
随机阅读: