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

167
Vistas
Pregmatch last instance of a word

I want to know how I can match the word/s after the last instance of by. For example below I have a list of $books. The book is in the format <book title> by <author> The book title can contain any character/s or nothing at all. However, the author can only be letters, numbers and underscores. I want to echo out the authors only.

I managed to do this with a combination of explode(), rtrim() and end() but how would I do this using preg_match / regex.

<pre><?php

$books = ['Big Blue Book by Steven', 'Dance by her by Mike', 'One day by by by', 'Hiphop Party by DJ340_Cool', ' by Paul12', 'by jasonB'];

foreach ($books as $book) {
    $temp = explode("by ", $book);
    $temp = rtrim(end($temp));
    echo("$temp\n");
}

The result I want:

Steven
Mike
by
DJ340_Cool
Paul12
jasonB
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You may use this code:

foreach ($books as $book) {
   if (preg_match('/^(?:.*\h)?by\h+(\S+)/', $book, $m))
      echo $m[1] . "\n";
}

Output:

Steven
Mike
by
DJ340_Cool
Paul12
jasonB

Here regex (?:^.*\h)?by\h+(\S+) matches last by surrounded with 1+ whitespaces on both sides due to use of greedy .* before. We capture 1+ non-whitespaces in 1st capture group and print it in if condition.

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