Home > Net >  preg_match exact world - no partial by array
preg_match exact world - no partial by array

Time:10-05

Hello everyone I made this php code

$variablename = "Marron";
$tallas = '#^/' . implode(array("XL", "L", "M", "S", "XS"), '|') . '/#';
if (preg_match($tallas, $variablename, $matchesatr)) {
$opciones = "Tallas";
} else {
$opciones = "Opciones";
}

Which results in M since it found the result M in the word Marron You can check this in $matchesatr

The problem here is that I need my preg_match to be very exact that I just need it to only match the value "M" if there is only that word.

Currently if the value of the variable begins or contains M returns true as a result.

I need you to be very sensitive to explain myself better.

If you find the value M of as true result.

If you find a word that starts with M or contains M of false result.

Of course, I have an array of words to search for, which would be: XL, L, M, S, XS

Additional note: I also need it to be case insensitive eg to detect "M" or "m"

CodePudding user response:

In your code, the regex delimiter is # at the outside of the pattern so you can remove the forward slash here #^/

Using implode the separator | is the first argument.

As you want to match any of the alternatives at the start of the string, you can use a grouping like a non capture group (?:...) to wrap the words.

If there can be nothing directly following the words, you can assert a whitespace boundary to the right with (?!\S) meaning that there should not be a non whitespace char directly to the right of the current position.

To make the pattern case insensitive, you can append i

The generated pattern looks like this:

^(?:XL|L|M|S|XS)(?!\S)

See a regex demo and a PHP demo.

A code example

$tallas = '#^(?:' . implode('|', array("XL", "L", "M", "S", "XS")) . ')(?!\S)#i';

$variablenames =  [
    "Marron",
    "m",
    "M"
];

foreach ($variablenames as $variablename) {
    if (preg_match($tallas, $variablename, $matchesatr)) {
        $opciones = "Tallas";
    } else {
        $opciones = "Opciones";
    }
    echo $opciones . PHP_EOL;    
}

Output

Opciones
Tallas
Tallas
  • Related