Jump to content

preg_match an array as pattern


dde
Go to solution Solved by requinix,

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
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;
Edited by dde
Link to comment
Share on other sites

  • Solution

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 by requinix
Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.