Reputation: 299
For example my input string is
$edition = Vol.123 or Edition 1920 or Volume 951 or Release A20 or Volume204 or Edition967
How can I check the words in string matches any word in the array.
$editionFormats = ['Vol','Volume','Edition','Release'];
Basically I need to check whether the input has Vol or Volume or Edition or Release.
Can anyone please provide a way to check the pattern?
I tried with str_pos()
, preg_grep()
, preg_match()
, split()
, str_split()
What I thought was to split the string after the first occurance of period or white space or numeric ,
but wasnt able to find it.
Upvotes: 0
Views: 48
Reputation: 71
Assuming your input is a single string (it wasn't obvious to me from the question)
A non regex way to do it is to look at the intersection between the set of words in the incoming string, and the set of words you're interested in:
$edition = 'Vol.123 or Edition 1920 or Volume 951 or Release A20'
$editionFormats = ['Vol','Volume','Edition','Release'];
// Break $edition into single words on, on space character.
$edition_words = explode(" ", $edition);
$present = !empty(array_intersect($edition_words, $editionFormats));
If you had meant that the $edition would be just one of those; i.e.
$edition = 'Volume 951'
This approach will still work; Note that splitting on the space character only works if there is a space, so your 'Vol.123' wouldn't get matched, unless you also included 'Vol.' in your $editionFormats.
Upvotes: 0
Reputation: 54796
Solution with regexp:
$edition[] = 'Vol.123';
$edition[] = 'Edition 1920';
$edition[] = 'Volume 951';
$edition[] = 'Release A20';
$edition[] = 'Unknown data';
$editionFormats = ['Vol','Volume','Edition','Release'];
$pattern = implode('|', $editionFormats);
foreach ($edition as $e) {
if (preg_match('/' . $pattern. '/', $e)) {
echo $e . ' matches' . PHP_EOL;
} else {
echo $e . ' NOT matches' . PHP_EOL;
}
}
Upvotes: 2