-3

Consider

preg_replace('/(lets go).*/', "going", "lets go somewhere")

It will output: "going", I want "going somewhere".

preg_replace seems to replace using the first match which is the whole string "lets go somewhere". How can I make it ignore index 0 and only target index 1?

ajthinking
  • 3,386
  • 8
  • 45
  • 75

1 Answers1

5

I don't know what you want to match with .*. You don't need it. This will work fine:

preg_replace('/(lets go)/', "going", "lets go somewhere");

Or you can use a lazy match:

preg_replace('/(lets go).*?/', "going", "lets go somewhere");

Explanation: Your original expression was greedy. That roughly means that .* matches as many characters as possible. .*? is lazy; it matches the minimum amount of characters.

You can also match 'somewhere' as a sub-pattern, and us it in the replacement:

preg_replace('/(lets go)(.*)/', "going\$2", "lets go somewhere");

Here. $0 is "lets go somewhere", $1 is "lets go", $2 is " somewhere". The backslash is needed because "going\$2" is inside double quotes.

jh1711
  • 2,288
  • 1
  • 12
  • 20
  • The lazy match solves my problem ( .* just illustrates some more content in the regex). Im not sure I understand it though its OUTSIDE of the paranthesis so it shouldnt be matched at all no mather what? Edit: i guess there is a difference between capturing and matching I need to grasp. Thanks! – ajthinking May 13 '18 at 18:44
  • 1
    The parentheses group sub-patterns. `preg_replace` will replace the entire pattern. But could also use a sub-pattern as a replacement. I'll put an example in my answer. – jh1711 May 13 '18 at 18:49