1

I have a long string containing Copyright: 'any length of unknown string here',
what regex should I write to exactly match this as substring in a string?

I tried this preg_replace('/Copyright:(.*?)/', 'mytext', $str); but its not working, it only matches the Copyright:

Uttara
  • 2,496
  • 3
  • 24
  • 35

2 Answers2

3

A lazily quantified pattern at the end of the pattern will always match no text in case of *? and 1 char only in case of +?, i.e. will match as few chars as possible to return a valid match.

You need to make sure you get to the ', by putting them into the pattern:

'/Copyright:.*?\',/'
               ^^^

See the regex demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

The ? in your group 1 (.*?) makes this block lazy, i.e. matching as few characters as possible. Removing that would solve it.

Copyright:(.*)',

However, that would match everything in that same line. If you have text in that same line, make sure to limit it further. My screenshot below just just grouping () to make it easier for you to look, you can do without the parentheses.

Demo

I usually use Regxr.com to test my regular expression, there's also many other similar tools online, note that this one is great in UX, but does not support lookbehind.

Community
  • 1
  • 1
Hung Tran
  • 1,570
  • 1
  • 13
  • 13