Jump to content

preg_match specific characters?


Edward

Recommended Posts

I'm not entirely sure I understand your question either; you want to limit the contents of a variable to certain characters? If that's correct, you can just throw them in a character class like so:

$test = 'aeiou but sometimes y';
if( preg_match('/^[aeiou]+$/', $test) ){
   echo 'Esta bueno!'; // Cheesy attempt at humor, just watched 'Man on Fire'
}else{
   echo 'No Good!';
}

Here's a quick breakdown of what I'm doing here:

  • preg_match('/^[aeiou]+$/', $test) -- Anchors the match to the beginning of the string
  • preg_match('/^[aeiou]+$/', $test) -- Here's your character class, these are the characters you want to allow
  • preg_match('/^[aeiou]+$/', $test) -- This says match one or more of the characters in the preceding class
  • preg_match('/^[aeiou]+$/', $test) -- This is the end of line anchor, basically makes the match have to match from the beginning to the end of the string.

 

Check the links in either effigy's or my signature for some info/tutorials on regex.

Hope this helps!

There's also locales, which I get tangled up in myself.

 

Typically, for example, \w only matches [a-zA-Z0-9_]. This can change based on the locale, which would (still) only include one language. A broader approach is to use Unicode syntax, and more specifically properties (\p{...} or \P{...}), which are language independent.

 

The ASCII way: [a-zA-Z], which matches literal characters.

The Unicode way: \p{L}, which matches characters that have the property of "L", which is short for "Letter."

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.