Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!