ZeroNine
ZeroNine

Reputation: 792

Preg Match a string with $, numbers, and letters

I'm trying to preg_match this string.

$word = "$1$s"; 
or 
$word = "$2$s"

if(preg_match('/^\$[1-9]{1}\$s$/' ,$word)){
   echo 'true';
} else {
  echo 'false';
}

I tried this but it is not giving a true result. How can I make this true.

Upvotes: 1

Views: 59

Answers (2)

Sam
Sam

Reputation: 20486

PHP is trying to render the variable $s in the double quoted string. Use single quotes instead and you can remove the {1} inside your regular expression because it is not necessary.

$word = '$1$s';

if (preg_match('/^\$[1-9]\$s$/', $word)) {
    echo 'true';
} else {
    echo 'false';
}

You can also escape the $ in your double quoted string:

$word = "$1\$s";
// Note $1 doesn't need to be escaped since variables can't start with numbers

Finally, you can see why this wasn't working by seeing what your $word actually equaled (with error reporting enabled):

$word = "$1$s"; // Notice: Undefined variable: s on line #
echo $word;     // $1

Upvotes: 4

Adrian B
Adrian B

Reputation: 1631

Try this:

if(preg_match('/\$[1-9]{1}\$s/',$word)){
    echo 'true';
} else {
    echo 'false';
}

Upvotes: -1

Related Questions