Jump to content

preg_match an array as pattern


dde

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/293955-preg_match-an-array-as-pattern/
Share on other sites

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;

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".

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?

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.