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

260
Visualizações
How to get last strings starts with '@' and numbers in PHP?

I need to extract all whitespace separated "words" at the end of string that either start with the @ character or that consist solely of digits.

For example, I have this string:

hello @tag1 111 world @tag2 @tag3 222 333

I need to obtain

@tag2 @tag3 222 333

I have used this code below:

preg_match_all('~\B@\S+|\b\d+\b~', $string, $match);

With this, I'll get all strings that started with '@' character and numbers, even @tag1 and 111.

I also tried the code below:

$str = 'hello @tag1 111 world @tag2 @tag3 222 333';
$exp = explode(' ', $str);
$arraysfordelete = [];
foreach ($exp as $num => $user) {
    if (!preg_match('~\B@\S+|\b\d+\b~', $user, $match)) {
        array_push($arraysfordelete, $num);
    }
}
$array = array_slice($exp, end($arraysfordelete) + 1);
echo implode(' ', $array);

Any suggestions?

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

0

Here is the PHP solution you need:

$str = 'hello @tag1 111 world @tag2 @tag3 222 333';
if (preg_match('~(?<!\S)(@\S+|\d+)(?:\s+(?1))*(?=\s*$)~', $str, $m)) {
    echo $m[0];
}
// => @tag2 @tag3 222 333

See the regex demo. Details:

  • (?<!\S) - a location that is either right after a whitespace or start of string
  • (@\S+|\d+) - Group 1: @ and one or more non-whitespace chars or one or more digits
  • (?:\s+(?1))* - zero or more occurrences of one or more whitespaces and then Group 1 pattern
  • (?=\s*$) - immediately to the right, there must be zero or more whitespaces and end of string.
over 4 years ago · Santiago Trujillo Relatório

0

You could use, for example

~[@\d]\S+~

which means match a @ or a digit, followed by one or more non-space characters \S+.

Or

~(?<!\S)[@\d]\S+~

if you want to make sure there is no non-space character preceding the @ or digit.

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