Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda