Search code examples
phpregexmatchcpu-word

php search on string comma separated and get element that match


I have a question, if anyone can help me to solve this. I have a string separated by commas, and I want to find an item that partially matches:

$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";

I need to get only the full string from partial match as a result of filter:

$result = "GenomaPrintOrder";

Solution

  • With preg_match_all you can do like this.

    Php Code

    <?php
      $subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
      $pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
      preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
      foreach ($matches as $val) {
          echo "Matched: " . $val[1]. "\n";
      }
    ?>
    

    Output

    Matched: GenomaPrintOrder
    Matched: NewPrintOrder
    

    Ideone Demo