ingteractive Posted July 29, 2014 Share Posted July 29, 2014 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! Quote Link to comment https://forums.phpfreaks.com/topic/290171-how-to-extract-a-list-of-grapes-from-a-string-using-preg_match/ Share on other sites More sharing options...
Solution Ch0cu3r Posted July 29, 2014 Solution Share Posted July 29, 2014 (edited) 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 July 29, 2014 by Ch0cu3r Quote Link to comment https://forums.phpfreaks.com/topic/290171-how-to-extract-a-list-of-grapes-from-a-string-using-preg_match/#findComment-1486382 Share on other sites More sharing options...
ingteractive Posted July 29, 2014 Author Share Posted July 29, 2014 you rock! Exactly what I was looking for. Topic closed! Quote Link to comment https://forums.phpfreaks.com/topic/290171-how-to-extract-a-list-of-grapes-from-a-string-using-preg_match/#findComment-1486397 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.