preg_match question

I don’t understand why these two expressions don’t both evaluate to 1. The first one evaluates to 0 and the second one to 1.

var_dump(preg_match("/[^a-zA-Z0-9\\_\\.]/", "word$test"));
var_dump(preg_match("/[^a-zA-Z0-9\\_\\.]/", "word*test"));

What is the significance of the $ that it isn’t seen as a match? Just for clarification, I want to evaluate to make sure there are no characters other than the alphanumeric and the _ and the . in the expression. If there are, I would expect it to evaluate to 1. Is this the correct syntax for that?


Have a look and see what echo "word$test"; outputs.

Then have a read of variable parsing in strings.

Then finally, run your code above with this line preceding it: error_reporting(-1);

Wow, that was a real “aha” moment. Thanks for the heads up. That explains everything and some other things also. :slight_smile:

I tried assigning a variable a value with single and double quoted text with the $ and it behaves exactly like I would expect; a match with the single quote, no match with the double quote.

If I assign a user input $_POST to the variable and the user includes a $ in their input, how does PHP handle that? I would assume for safety reasons it is treated the same as the single quoted variable. I will try it but was just wondering if maybe that was a broader question?

That would be absolutely fine, the so called “variable parsing” within double-quoted string only happens for the code that you write. Values brought in from elsewhere (e.g. a form) with dollar symbols won’t get the same treatment; they don’t contain variables to be parsed.

Really, the double-quoted string is there just to allow (arguably) cleaner code, or just less typing.

$who  = "world";
$when = "today";
// Both lines below produce the same output
echo "Hello $who, how are you $when?";
echo 'Hello ' . $who . ', how are you ' . $when . '?';

Got it. Thanks so much for the help.