Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
Sanitize phone number: regular expression match all except first occurence is on first position

regarding to this post "https://stackoverflow.com/questions/35413960/regular-expression-match-all-except-first-occurence" I'm wondering how to find the first occurence on a string only if it start's with a specfic character in PHP.

I would like to sanitize phonenumbers. Example bad phone number:

+49+12423#23492@aosd#+dasd

Regex to remove all "+" except first occurence.

\G(?:\A[^\+]*\+)?+[^\+]*\K\+

Problem: it should remove every "+" only if it starts with "+" not if the first occurence-position is greater than 1.

The regex to remove everything except numbers is easy:

[^0-9]*

But I don't know how to combine those two within one regex. I would just use preg_replace() twice.

Of course I would be able to use a workaround like if ($str[0] === '+') {...} but I prefer to learn some new stuff (regex :)

Thanks for helping.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use

(?:\G(?!\A)|^\+)[^+]*\K\+

See the regex demo. Details:

  • (?:\G(?!\A)|^\+) - either the end of the preceding successful match or a + at the start of string
  • [^+]* - zero or more chars other than +
  • \K - match reset operator discarding the text matched so far
  • \+ - a + char.

See the PHP demo:

$re = '/(?:\G(?!\A)|^\+)[^+]*\K\+/m';
$str = '+49+12423#23492@aosd#+dasd';
echo preg_replace($re, '', $str);
// => +4912423#23492@aosd#dasd
over 4 years ago · Santiago Trujillo Relatório

0

You seem to want to combine the two queries:

A regex to remove everything except numbers

A regex to remove all "+" except first occurence

Here is my two cents:

(?:^\+|\d)(*SKIP)(*F)|.

Replace what is matched with nothing. Here is an online demo


  • (?:^\+|\d) - A non-capture group to match a starting literal plus or any digit in the range from 0-9.
  • (*SKIP)(*F) - Consume the previous matched characters and fail them in the rest of the matching result.
  • | - Or:
  • . - Any single character other than newline.

I'd like to think that this is a slight adaptation of what some consider "The best regex trick ever" where one would first try to match what you don't want, then use an alternation to match what you do want. With the use of the backtracking control verbs (*SKIP)(*F) we reverse the logic. We first match what we do want, exclude it from the results and then match what we don't want.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda