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