0

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";
4
  • 1
    Have you tried anything with preg_match ? Commented Mar 22, 2016 at 14:56
  • If you know how the aggregate string has been glued together, you can use that glue to explode that string into an array and loop over it. Commented Mar 22, 2016 at 14:57
  • $matches = array_filter(explode(',', $string), function ($value) use ($search) { return strpos($value, $search) !== false; }); Commented Mar 22, 2016 at 15:01
  • You might want to consider upvoting good answers even if you didn't accept them, I did. Commented Mar 28, 2016 at 19:00

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

get this error: Warning: preg_match(): Compilation failed: nothing to repeat at offset 25
@WalterNuñez: I have edited the code. Please check. In the latest example I have added an extra string NewPrintOrder to demo multiple matches.
1
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
    if(strpos($entrie, $string) !== false)
        $result[] = trim($entrie);
}

This will get you an array with all strings that match your search-string.

Comments

1

You can use regular expression to get the result:

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

$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';

preg_match($regex, $string, $match);

$result = trim($match[1]); // $result == 'GenomaPrintOrder'

Comments

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


$array = explode(" ", $string);
echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });

Comments

1

Since there are so many different answers already, here is another:

$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);

Comments