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

165
Visualizações
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 Respostas
Responde à pergunta

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 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