Reputation: 241
Hello everyone I am trying to create a regexp for PHP that will allow me to get the quote and the author. I have made it work if everything is one line but the moment it is put in multiple lines it stops working. What am I doing wrong?
(\[quote\])(.*)(\|)(.*)(\[\/quote\])
[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children's rhyme[/quote]
[quote]Silence you sleep.|-popular children's rhyme[/quote]
Upvotes: 1
Views: 1045
Reputation: 350079
Use the s
modifier (append if after the regex delimiter). Also, make your .*
non-greedy by adding a ?
:
preg_match_all("~\[quote\](.*?)\|(.*?)\[/quote\]~s", $s, $results, PREG_SET_ORDER);
Output is in $results
:
[
[
"[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children's rhyme[/quote]",
"Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.",
"-popular children's rhyme"
], [
"[quote]Silence you sleep.|-popular children's rhyme[/quote]",
"Silence you sleep.",
"-popular children's rhyme"
]
]
Upvotes: 5
Reputation: 22817
\[quote\](.*?)\|-(.*?)\[\/quote\]
Note: The regex above uses the s
modifier. Alternatively, you can replace .
with [\s\S]
and disable the s
modifier
$re = '/\[quote\](.*?)\|-(.*?)\[\/quote\]/s';
$str = '[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children\'s rhyme[/quote]
[quote]Silence you sleep.|-popular children\'s rhyme[/quote]';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
[quote]Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.|-popular children's rhyme[/quote]
[quote]Silence you sleep.|-popular children's rhyme[/quote]
The output below is organized by group (separated by newline)
Silence in the boatyard, Silence in the street, The Locks and Quays of Haganport Will rob you while you sleep.
popular children's rhyme
Silence you sleep.
popular children's rhyme
\[quote\]
Match this literally (backslashes escaping the following character)(.*?)
Capture any character any number of times, but as few as possible into capture group 1\|-
Match this literally (backslashes escaping the following character)(.*?)
Capture any character any number of times, but as few as possible into capture group 2\[\/quote\]
Match this literally (backslashes escaping the following character)Upvotes: 3