RandomUser
RandomUser

Reputation: 4220

preg_match issues using php variable

I have a variable I want to use in a preg_match combined with some regex:

$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
    echo "matched";
}

In my pattern I am trying to match using cheese, followed by a - and 1 digit, followed by anything else.

Upvotes: 2

Views: 7375

Answers (3)

Shahrokhian
Shahrokhian

Reputation: 1114

  1. change /d to \d
  2. there is no need to use .*
  3. if your string is defined by user (or may contains some characters (e.g: / or * or ...)) this may cause problem on your match.

Code:

<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string)) 
{
    echo "matched";
}
?>

Upvotes: 4

jaudette
jaudette

Reputation: 2303

for digit, it's \d

if(preg_match("/$find-\d.*/", $string)) {

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191829

You mistyped / for \:

if(preg_match("/$find-\d.*/", $string)) {

The .* is also not really necessary since the pattern will match either way.

Upvotes: 3

Related Questions