Jump to content

preg_match specific characters?


Edward

Recommended Posts

 

Is it possible to sppecify which characters you allow in a variable? For example, only letters and numbers, or only lettes with the hyphen character, or only characters a, b, c, x, y, z, !, -

 

Thank you.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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."

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.