0

I have the following code:

<?php
    $subject="something";
    $pattern="something";
    If(preg_match($pattern,$subject)){
        echo "Match is found";
    }else{
        echo "Match is not found";
    }
?>

If I have

$subject="apple is fruit and I love apple";

The main point being the string beginning with apple and ending with apple

Then what should be the pattern so that

match is found

is the output.

I know the pattern can be

"/^apple.*apple$/"

But I don't want to repeat the same word apple.

24
  • You don't want to repeat the substring "apple"? Put it in a variable: $word = "apple";, or use sprintf to build your pattern. Commented Jun 9, 2017 at 17:13
  • This cannot be the answer as then I have to repeat $word variable Commented Jun 9, 2017 at 17:14
  • 3
    I think you want something like this: ^(\w+)\b.*\b\1$ Basically, start with a word (\w+) and then a word boundary. Whatever is in the (\w+) must then be at the end, which is the \1 I'm not sure what the \1 syntax is in php, this is for Python. Maybe $1 ? Commented Jun 9, 2017 at 17:15
  • 1
    I feel OP needs "/^(apple).*(?1)$/s" (due to I don't want to repeat the same word apple.) Commented Jun 9, 2017 at 17:21
  • 1
    @chris85: Only in case apple is in fact a placeholder for some other pattern, e.g. <<[A-Z]{3}>>. But not really sure, the question is rather weird. I just do not see any issue. Closing it as primarily opinion-based. Commented Jun 9, 2017 at 17:42

1 Answer 1

0

You just need a backreference. Try:

/^(\w+).*(\1)$/

The (\w+) captures the first word, no matter what it is, without having to specify "apple" as the word. The backreference, \1 tells the regex parser to substitute in whatever was captured in the first capture group. Using the magic of backtracking, the regex parser will figure out how to fit match the input symbols correctly to satisfy the backreference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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