2

For a special function to build better and smarter PDO statements I've matched and extracted every word, which started with a colon.

PHP like Needle: /:\w+/

But sometimes it also happens that I've to handle strings with colon-seperated digits. (time-values)

  • 2018-05-21T00:00:00+02:00
  • 00:00:00
  • 00:00

I've tried to exclude them, but never succeeded when I tried to extend my regex-needle for this. Because of that issue, I just often workaround this issue. But now I would like to fix and understand how to solve this.

The condition sounds easy

  1. Find every word, which starts with a colon.
  2. Remove every match which has digits before the colon.

So from the current result with :\w+:

:light at 07:15:0000

I would like just to match:

:light at 07:15:0000

Sascha
  • 615
  • 1
  • 9
  • 20

2 Answers2

3

If those substrings after : cannot start with a digit, you may use

:[A-Za-z_]\w*

See the regex demo.

Here,

  • : - a colon
  • [A-Za-z_] - a letter or _ (remove _ if the first char can only be a letter)
  • \w* - 0+ letters, digits or/and _

Alternatives

You also may match those time-like strings, and match and capture :\w+:

\d+:\d+(?::\d+)?|(:\w+)

See the regex demo. Only grab Group 1 values if Group 1 matches.

In PHP, you may achieve exactly what you need with a SKIP-FAIL regex:

'~\d+:\d+(?::\d+)?(*SKIP)(*F)|:\w+~'

See another demo.

With (*SKIP)(*F), you can match and skip the matches while matching the rest of the alternatives.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • It's just funny that I wasn't able to think about the almost easiest solution like both of you (Wiktor, Andreas) suggested: Using character-ranges instead of word-matching. Thank you! – Sascha Jul 30 '18 at 13:36
2

You don't need to use "/:\w+/" you can use "/:[a-zA-Z]+/"that wont capture times.

Andreas
  • 23,610
  • 6
  • 30
  • 62
  • It's just funny that I wasn't able to think about the almost easiest solution like both of you (Wiktor, Andreas) suggested: Using character-ranges instead of word-matching. Thank you! – Sascha Jul 30 '18 at 13:36