With PHP/Preg, how is it possible to replace a string not followed by any character

46 Views Asked by At

For example, I have two strings

  1. "abcdef"
  2. "abcdefghijk"

I want to replace the first one, but not the second one which begins with the same string. However, the first one can be followed by any ponctuation such like , ; ? . and so on. So, I have to replace abcdef only, if there is no other character A-Z, a-z, after the string.

I probably have to use preg_replace, but I don't see how to write my regex string to exclude the strings followed by any character.

I tried of course to replace the string without to take care of the characters following this string, and it is running of course. str_replace is enough for that, but it is not enough in my case.

1

There are 1 best solutions below

0
Toto On

Use a negative lookahead that makes sure we haven't letter after the match.

\babcdef(?![a-zA-Z])

Demo & Explanation