Is it possible to remove the first sequence of the last letter of the regex?

Asked

Viewed 174 times

3

I need help on something very specific, which involves good interpretation, is the following, I need to inform a word on regex example nt the last letter that would be t was extended to the first sequence of t's and stop, for example...

in

$txt = "nttttouterttt";

echo preg_replace('/nt/', '', $txt);

saida: tttouterttt

expected result

$txt = "nttttouterttt";

echo preg_replace('/nt/', '', $txt);

saida: outerttt

if the next letter does not outside’t', does not continue the sequence

$txt = "ntptttouterttt";

echo preg_replace('/nt/', '', $txt);

saida: ptttouterttt

nt is removed but would like to remove the nt>ttt< entire, remaining only outerttt, case the string outside ntptttouterttt it would withdraw only nt, is it possible? there would be another method? I accept suggestions and material...

  • 1

    please give some examples of input and their respective outputs so that we can analyze their logic in action, it is easier to deliver something correct ;)

  • @Paz, really, I’ve already edited.

  • 2

    In the first case, instead of nt, tried to use the n[t]+? Or n[t]*? Where you use the Quantifier +, which will match between one and unlimited times the operator t or * which corresponds from zero to unlimited times.

  • 1

    Serious guy that this? I tested here and it seems to me that it worked, I thought it would be bigger complication kk, thank you very much vei...

  • @danieltakeshi posted as answer to Felipe accept, so if other people have the same question and arrive here via research can see easier.

1 answer

5


The Regex used is nt+ or the nt*, with the demo on Regex101.

Where the Regex101 site can be used to test Regexes, widely used because of the formatting colors, simple design and ease of use.

Explanation

nt+ Validates the part of the String that starts with n and has at least one t to infinities

  • n - Corresponds literally to the character n
  • t - Corresponds literally to the character t.
  • + - Quantifier that corresponds from one to unlimited times, as many times as possible (Greedy).

nt* Validates the part of the String that starts with n and does not necessarily possess t to infinities t

  • n - Corresponds literally to the character n
  • t - Corresponds literally to the character t.
  • * - Quantifier that corresponds from zero to unlimited times, as many times as possible (Greedy).
  • 1

    The brackets were unnecessary. You could only quantify t without having to put it in a selection. As regex nt+ and nt* are equivalent to what you wrote

  • 1

    True, I’ll edit it. It was customary to put more things in and make clear what is being quantified.

  • Concise response and perfectly meets +1 requirements

Browser other questions tagged

You are not signed in. Login or sign up in order to post.