Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

PHP regex to allow only two chars

I need a regex to recognize only two options, they are 'F' and 'M' chars. I am trying:

preg_replace('/([^FM]){1}/', '', $_GET['option'])

But if i type 'MF' it returns 'MF', but i am expecting 'M'.

Can anybody help me?

Upvotes: 1

Views: 349

Answers (2)

amlane86
amlane86

Reputation: 668

Could always try this. It's a one liner and will grab the first character of the string. If 'm' or 'M' it will return 'M'. and same goes for female. If nothing matches then it will return ''.

$gender = strtolower(substr($_GET['option'], 0, 1)) == 'f' ? 'F' : (strtolower(substr($_GET['option'], 0, 1)) == 'm' ? 'M' : '');

Upvotes: 0

Martin Ender
Martin Ender

Reputation: 44259

$output = preg_replace('/^[^FM]*([FM])?.*/s', '$1', $_GET['option']);

Start at the beginning of the string. Consume all non-FM characters. Then match one F or M character (if there is one). Match the rest of the input. Replace with the matched character. Note that you will end up with an empty string if there was no M or F at all.

However, you should probably rethink how you get that data, since it seems to be a boolean value (but you take care of an arbitrary string that might contain the desired characters).

If you generate the value yourself (from some other website), you should be able to know that values that haven't been tampered with are either "M" or "F". So why not just go with:

if ($_GET['option'] == "M")
    // male...
elseif ($_GET['option'] == "F")
    // female...
else
    // someone tried to mess with you ...

Upvotes: 1

Related Questions