Jump to content

How to extract a list of grapes from a string using preg_match


Go to solution Solved by Ch0cu3r,

Recommended Posts

Can anyone help me output "Zinfandel|Sauvignon Blanc" from "This very nice wine is produced in California and is made from Zinfandel and Sauvignon Blanc grapes."?

Please also notice the case insensitivity. I prefer the output with capitals on first words. 

 

I created the following code :

<?php 
$ds = "Riesling|Sauvignon Blanc|Zinfandel|Muscat/i";
$string = "This very nice wine is produced in California and is made from zinfandel and Sauvignon Blanc grapes.";

echo "This is the string to extract the grapes from : ";
echo $string;
echo "<br>";

echo "These are the grapes that need to be matched in a regular expression : ";
echo $ds;
echo "<br>";

$matches = array();
$search = preg_match_all($ds, $string, $matches);

foreach ($matches[1] as $match) {
    echo $match;
	// I want this to output "Zinfandel|Sauvignon Blanc" with a pipeline between the matches
}
?>

Any help pretty much appreaciated!

  • Solution

You need to fix you regex first.

 

All regex patterns need to be enclosed in delimiters. You have left off the opening delimiter (in your case a forward slash / )

 

As you are wanting to match complete words you'll want to wrap the list of grapes in a word boundary

$ds = "/\bRiesling|Sauvignon Blanc|Zinfandel|Muscat\b/i"; 

Finally to return the matched words in a pipe separated list you can implode $matches[0] as this will contain an array populated with the matched words. Note if a word is found more than once it will be listed again (duplicated) in the array. If you want to return each unique word found then pass $matches[0] to array_unique first before imploding the array

echo "<p>These grapes were used in the string:<br />" .  implode('|', array_unique($matches[0]));
Edited by Ch0cu3r
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.