dde Posted January 15, 2015 Share Posted January 15, 2015 I'm trying to preg_match $text for specific words, defined in an array.$text = "PHP is a programming language of choice"; $text = "This is a function written in a programming language called PHP."; $words = array("/java/", "/PHP/", "/html/"); for ($i = 0; $i < count($words); $i++) { preg_match($words[$i], $text, $matches); } The problem with tis is that it returns 3 arrays, of which only the second one is a match, and the other 2 arrays are empty.The result is that I get notice error on my echo page because the 1st and 3rd arrays are empty.if I want the text to be searched for the first matching result, whether it is java, PHP or html, then stop (if possible) and echo/return the result, how will I do that? Perhaps preg_match is not to be used here but instead something like substr? Quote Link to comment Share on other sites More sharing options...
dde Posted January 15, 2015 Author Share Posted January 15, 2015 (edited) So far I got this, but when having lots of words, the code becomes too big. Is it possible to have the words in an array? if(preg_match("/java/", $text)) { $match = "java"; } elseif(preg_match("/PHP/", $text)) { $match = "PHP"; } elseif(preg_match("/html/", $text)) { $match = "html"; } else { $match = "unknown programming language"; } echo $match; Edited January 15, 2015 by dde Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted January 15, 2015 Solution Share Posted January 15, 2015 (edited) Maybe you're looking for "alternation"? if(preg_match('/java|PHP|html/', $text, $match)) { echo "Found ", $match[0]; // 0 is the entire string that was matched, so "java" or "PHP" or "html"The pipe separates different parts of the regex that can match. A|(B|C)D matches "A" or "BD" or "CD". Edited January 15, 2015 by requinix Quote Link to comment Share on other sites More sharing options...
dde Posted January 15, 2015 Author Share Posted January 15, 2015 Maybe you're looking for "alternation"? if(preg_match('/java|PHP|html/', $text, $match)) { echo "Found ", $match[0]; // 0 is the entire string that was matched, so "java" or "PHP" or "html"The pipe separates different parts of the regex that can match. A|(B|C)D matches "A" or "BD" or "CD". It would not be possible to have patterns in an array? Quote Link to comment Share on other sites More sharing options...
requinix Posted January 15, 2015 Share Posted January 15, 2015 No, that is not supported. If you want an array then just use a loop, it's hardly any more work. Quote Link to comment 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.