2

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.

0

3 Answers 3

4
  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";
}
?>
Sign up to request clarification or add additional context in comments.

Comments

3

You mistyped / for \:

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

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

Comments

1

for digit, it's \d

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.