Jump to content

Filter Text


smerny

Recommended Posts

is there a way to have a boolean on whether or not a variable contains characters that are not alphabet/number?like $name1= "JAne32j"$name2 = "sad"a function i could run on these that would be true or false depending on if it has invalid characters?

Link to comment
Share on other sites

could you show me an example? i looked at preg_match on the php manual and it seems more about finding particular characters rather than making sure there are only letters and numbers.... the only way i can think of to use that would be to individually search each character that i dont want and see if it has any... but that would take many many lines...

Link to comment
Share on other sites

Regular expressions are more flexible than you may imagine. Consider:

$subject = "abc123";$pattern = '/[a-zA-Z0-9]/';$result = preg_match($pattern, $subject);

$result returns true because the first character of $subject matches one of the three character ranges in $pattern. This is a pretty useless regex. The one below is one you could actually use:

$subject = "abc*123"; $pattern = '/[^a-zA-Z0-9]/'; $result = preg_match($pattern, $subject);if ($result) {	// we have an illegal character}

$result returns true because the pattern is different. The ^ inside the brackets says we're looking for all characters that are NOT in the ranges. Since the * is not in any of the ranges, we have a match. It's a logic thing. We have a "match" because we found what is NOT specified in the pattern.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...