Issue
I am trying to work out whether or not a $string contains a particular $string and NOT contain multiple other $strings… I need to assign a code depending on what colors are involved..
just balloon = 1, red = 2, blue = 3, green = 4, red blue = 5, red green = 6, blue green = 7,
red blue green = 11 (all colours)
this has been simplified for this example as there are 6 colours and I have to repeat this for 10 objects…
I thought I could use some sort of combimation of stros & preg_match:
$mystring = "red blue balloon";
if((strpos($mystring, 'red') !== false) {$code = 2;}
else if((strpos($mystring, 'blue') !== false) {$code = 3;}
else if(preg_match('(red|blue)', $mystring) === 1) {$code = 5;} // etc for each perm
else {$code = 1;} // just balloon
but I realised that this code doesn’t really work and it will require many lines of code for each permutaion…
Is there a nice tidy way I can assign the codes. I have to repeat this with many colors and many different objects…
If you can point me in the right direction, I’d be very grateful. Thanks very much in advance
Solution
You can accumulate points as you check for individual words. If all three colors are found, award 2 bonus points. Your example is ambiguous about scoring the balloon, so I am interpreting your needs as only counting balloon if there are no colors.
You should use case-insensitivity for flexibility and word boundaries to ensure that you are matching whole words.
Code: (Demo)
function getCode($string) {
$code = 0;
if (preg_match('/\bred\b/i', $string)) {
$code += 2;
}
if (preg_match('/\bblue\b/i', $string)) {
$code += 3;
}
if (preg_match('/\bgreen\b/i', $string)) {
$code += 4;
}
if ($code === 9) {
$code += 2;
}
if ($code) {
return $code;
}
if (preg_match('/\bballoon\b/i', $string)) {
return 1;
}
return 0;
}
$sentences = [
'Here is a green, blue, and red balloon',
'A blue balloon here',
'A red herring',
'Blue is the name of my dog',
'Red and green are Xmas colors',
'blue skies over green grass',
'Foo is bar',
'Have a balloon and a balloon and a balloon',
'A green balloon',
'A blue balloon with a red string',
];
foreach ($sentences as $sentence) {
printf("%s => %d\n", $sentence, getCode($sentence));
}
Output:
Here is a green, blue, and red balloon => 11
A blue balloon here => 3
A red herring => 2
Blue is the name of my dog => 3
Red and green are Xmas colors => 6
blue skies over green grass => 7
Foo is bar => 0
Have a balloon and a balloon and a balloon => 1
A green balloon => 4
A blue balloon with a red string => 5
Answered By – mickmackusa
Answer Checked By – Willingham (BugsFixing Volunteer)