views:

91

answers:

2

So here is what I'm doing exactly:

I have a form with a caption on the right of it, I want to write in the form only A-Z,0-9 and whitespaces, and for the caption I want to do the opposite, so if the user write's something wrong I can show what's the problem for example: "Invalid Charachter"

But I'm stuck with + and # I want to ignore them too from the form with regular expression so I can show the "Invalid character" message for these too, as I saw php thinks that + sign is = to space ( ) or what, but I need to ignore + and # signs too. This is my current code:

preg_match_all("/[^\w\s]/",$string,$matches);


foreach($matches[0] as $ic){
     if(strpos($str,$ic) || $str[0] == $ic){
          $fullname_error = "Invalid Character";
     }  
}

Valid strings:

  • John Doe
  • Mary Sue

Not valid strings:

  • J#ohn Doe
  • John&Doe
  • John+Doe
  • Mar@y+Sue
  • !Mary Sue
  • Mary Sue!
+1  A: 

Try this:

<?
function checkString($str)
 {
 echo "Testing ".$str."<br />";
 // Check if there are invalid characters
 if (!preg_match("/^[a-zA-Z0-9\s]+$/", $str))
  {
  echo "Oh no! There are invalid characters! :(<br />";
  }
 else
  {
  echo "There is no invalid character!!! :)<br />";
  }

 // What are the invalid characters?
 if (preg_match("/[^(a-zA-Z0-9\s)]/", $str, $matches))
  {
  echo "Invalid character: ".$matches[0]."<br />";
  }
 }

checkString("This is a good string");
checkString("This is a not a good string$%#@#$"); 
?>
nico
Hmm let me try it
CIRK
@Cirk: The regexp I wrote check also for `+`. They check for anything which is not A-Z, a-z, 0-9 or a space, so `+` is included. I was saying that `+` has a special meaning in regexp, that's all. If you were to include it you would just escape it with a slash `\+`
nico
Doesn't works, now for characters like `@$% I don't see the 'Invalid Character' caption.. and +$ is to search in the end as I know, I want to search it anywhere in the string. Sorry I'm new in regex :P
CIRK
@Cirk: Maybe you did something wrong in PHP... I edited my answer with some tested PHP code. As you can see it does work
nico
let me see it ;) Umm.. and I use AJAX to see the captions maybe it helps
CIRK
@Cirk: for better understanding of what you want, you should post some examples of valid and invalid strings.
jigfox
@Cirk: Try to see if it works without AJAX first, then add AJAX. Maybe it's just a problem of how you send the string to the page called via AJAX.
nico
CIRK
I'm trying @nico ;)
CIRK
Ahh finally I've made it to work, let me test it :D
CIRK
Ok I tested with this -> checkString("Th!is i)s a n(ot a g$od string$%#@#$"); and this is the result == Notice: Undefined variable: od in C:\wamp\www\pages\create_account.php on line 107Testing Th!is i)s a n(ot a g string$%#@#$Oh no! There are invalid characters! :(Invalid character: !There are a lots of invalid characters not just ! and the notice, I don't think if this is working how I want it, # and + are not showed as invalid characters too
CIRK
Sorry, my bad. PHP interprets `g$ood` as `g` and the variable `$ood`. So either you escape `$` as `\$` or you use single quotes.My regexp will check only the first invalid character, I'm sure there's a way to make it match all, but I can't just figure it out right now
nico
Ah, that's it! just use `preg_match_all` if you want to match all the invalid characters.
nico
Ok I've modified it to work because foreach is needed here: function checkString($str) { if (preg_match_all("/[^(a-zA-Z0-9\s)]/", $str, $matches)) { foreach($matches[0] as $m){ echo "Invalid character: ".$m[0]."<br /><br />"; } } } checkString("Th!is i)s a n(ot a g$od string$%#@#$++"); Now this is the result:Invalid character: !Invalid character: $Invalid character: %Invalid character: #Invalid character: @Invalid character: #Invalid character: $Invalid character: +Invalid character: +
CIRK
But now I have the same what I was posting in the question in a longer way :)), [^(a-zA-Z0-9\s)] is the same as [^\w\s]
CIRK
Yes, of course you need `foreach` if you want to parse all the matches. I strongly advice NOT to write the string "Invalid character" each time though... makes it hard to read. Just write it once out of the loop and then write the wrong characters. PS: use backticks (```) to format code in your comments.
nico
It's is showed just one time don't worry :D
CIRK
@Cirk: `[^(a-zA-Z0-9\s)]` is equivalent to `[^\w\s]` but slightly more flexible if you want to allow/disallow other chars. Anyway if it works...
nico
Thanks for the help @nico !! If I could accept two answers I would accept yours too but @Gumbo has resolved my problem in my last question too I'm just noob :D and tanks for the ``` tip
CIRK
+1  A: 

You could do something like this to handle the invalid characters:

$str = 'gum@#+boo';
if (preg_match_all('/[^\w\s]/u', $str, $matches)) {
    echo sprintf(
        '<p>Your input <b>%s</b> contains %d invalid character%s: <b>%s</b>.</p>',
        htmlspecialchars($str),
        count($matches[0]),
        count($matches[0]) > 1 ? '' : 's',
        implode('</b>, <b>', array_map('htmlspecialchars', array_unique($matches[0])))
    );
    echo '<p>Please choose a different input value.</p>';
}
Gumbo
Still doesn't works for `#` and `+` for me
CIRK
@Cirk: What do you mean by it doesn’t work for `#` and `+`? If `$str` contains any other character except word characters (`\w`) or whitespace characters (`\s`) the regular expression will match those characters.
Gumbo
for example: I wrote `gum@#+boo` and your script says: `Your input gum@ contains 1 invalid characters: @.`
CIRK
yepp and another interesting thing about `#`, it brakes the word as you can see here too. for example if I write `#gumboo` it says that it's too Short because I set the minimum of characters to 4, because of the `#` the php doesn't sees the others... :S
CIRK
@Cirk: Sorry, but using `$str = 'gum@#+boo';` yields the expected output of *Your input **gum@#+boo** contains 3 invalid character: **@**, **#**, **+**.* for me.
Gumbo
hmm good news, than I'm the idiot :D [as always]
CIRK
I tried in a separated file and works fine, you are true, hmmm I'm doing something wrong here.. But I don't know what everything seems ok.
CIRK
As I said before I use AJAX, ajax calls the php file into the caption div. can this be a problem?
CIRK
@Cirk: I don’t know what exactly you’re doing. But maybe you’re using the value in a URL and the `#` is interpreted as fragment separator. That would explain that only the first part is transmitted/available.
Gumbo
Ohh you are totally true, because I send the $str in a GET trought the ajax
CIRK
`preg_match_all("/[^\w\s]/",$string,$matches);` this is working cool too without the ajax... :D
CIRK
@Cirk: If you send the values via GET you have to encode the special characters.
Felix Kling
Yupiiiiiii I've encoded the values in javascript with `escape` and now works perfectly, thanks very very much!! Stackoverflow is awesome!!!
CIRK
@Cirk: Don’t use `escape` to encode data to be used in a URI, use `encodeURIComponent` instead.
Gumbo
Omg, you are awesome! xD `+` deson't worked with `escape`, now it works `+`too. Thanks thanks thanks!!
CIRK