I have a series of keywords I want to match against an item name to determine if it is a labor line item or not. How can I write the pattern regex so it matches them all in a more succinct block of code?
if(preg_match('/(LABOR)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(SERVICES)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Pull and Prep)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Supervision)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Coordination)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Disposal)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Handling)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Inspect)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Re-ship)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Storage)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Management)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Show Form)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Receive)/i', $Item[Name])){
$subtotal += $mysubtotal;
}elseif(preg_match('/(Paperwork)/i', $Item[Name])){
$subtotal += $mysubtotal;
}
The pipe, |
, with preg_replace
and its fifth parameter should be all you need.
preg_replace('/LABOR|SERVICES|Pull and Prep|Supervision|Coordination|Disposal|Handling|Inspect|Re-ship|Storage|Management|Show Form|Receive|Paperwork/i', '', $Item['Name'], -1, $subtotal);
You might want to use word boundaries as well so you know that it is an exact match (unless laboring, labors, etc are valid?):
preg_replace('/\b(?:LABOR|SERVICES|Pull and Prep|Supervision|Coordination|Disposal|Handling|Inspect|Re-ship|Storage|Management|Show Form|Receive|Paperwork)\b/i', '', $Item['Name'], -1, $subtotal);
If I have a list, A, of regexp's and I want to know if a string contains any of them, I can preg_match:
A[1] +"|"+ A[2] +"|"+ A[3]
Here, | is the "OR" or "Union" character for regular expressions and + is concatenation.
Just use |
(means OR).
So, your cole would look like this:
if(preg_match('/LABOR|SERVICES|Pull and Prep|...|.../i', $Item['Name'])){
$subtotal += $mysubtotal;
}
And, of course, don't forget to quote array keys (thanks to @mario): $Item['Name']
.
You can use |
as others suggested. Or, you can also try for in_array() and match with group 0 of the regex.
<?php
$desired_values = ['LABOR','SERVICES','Pull and Prep','Supervision','Coordination','Disposal','Handling','Inspect','Re-ship','Storage','Management','Show Form','Receive','Paperwork'];
$matches = [];
$string = "Pull and Prep";
if(preg_match('/.+/i',$string,$matches) && in_array($matches[0],$desired_values)){
$subtotal += $mysubtotal;
}