2

I feel I have a basic understanding of regex but I came across this conditional in our codebase the other day and I can't get my head around it:

if ($content && !preg_match('/{\w+}/', $content->title))

I was under the impression that the curly braces were min/max ranges and thus the \w+ doesn't really work inside but it doesn't error.

Currently it is letting through a $content->title of Unsubscribe which makes sense for our application, but would presumably match /\w+/.

Can anyone shed any light on this or should I rewrite it to something more sensible?

Arth
  • 11,500
  • 5
  • 32
  • 62
  • 2
    Next time you're confused throw your regex into here: https://regex101.com – Rizier123 Jul 02 '15 at 09:41
  • @Rizier123 Thanks, what a great resource – Arth Jul 02 '15 at 09:44
  • Pretty stunned that this question has been marked as a duplicate to what is essentially a regex manual. Shall I go over to all the basic MySQL questions and say 'This already has an answer hear' with a link to the MySQL docs homepage? The moderation on this site really annoys me sometimes... luckily I already have the answer I need. – Arth Jul 02 '15 at 15:44

2 Answers2

1

When you use characters {},regex engine assumes it as the characters { and } literally.but when it has a preceding token and a number within {} it interpreted as Limiting Repetition.So the following regex :

{\w+}

will match character { and then any combinations with length 1 or more of word characters then }

In One case it returns an error and its when you use a number within {} without preceding token.

kasravnd
  • 94,640
  • 16
  • 137
  • 166
1

{\w+} break-down:

{ and } matches { and } literally

\w+ match any word character ([a-zA-Z0-9_])

+ means one or more times

So {\w+} will match {someTextHere}

Justinas
  • 34,232
  • 3
  • 56
  • 78
  • Thanks, very helpful and would have been accepted, but I went for Kasra's answer because it addressed directly the exact issue that had confused me. – Arth Jul 02 '15 at 15:47