Jump to content

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


ingteractive

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!

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]));

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.