WraithLux
WraithLux

Reputation: 699

Regular expression, creating subpattern

I have two strings that I have to extract data from. I use preg_replace to do this. However, I'm not sure how to make it so that the last \s\:\: can either match or not. I tried {0,}, but then it doesn't match the first string, and without it the last string doesn't match.

$strings = array(
    '13.02 - foobar1 bla bla :: 08.03.2013 - 23.12.2013',
    '06.05 21:00 - " foobar2 bla bla "',
)

foreach($strings as $data){
    $pattern = '/^(\d){2}\.(\d){2}\s?(\d){0,2}(\:)?(\d){0,2}\s\-(.*)(\s\:\:.*)?/i';
    echo preg_replace($pattern, '$6', $data);
}

I expect to get these two strings as the final output:

"foobar1 bla bla"
"" foobar2 bla bla ""

Upvotes: 0

Views: 93

Answers (1)

Michael Sivolobov
Michael Sivolobov

Reputation: 13300

Your code should be like that:

$strings = array(
'13.02 - foobar1 bla bla :: 08.03.2013 - 23.12.2013',
'06.05 21:00 - " foobar2 bla bla "',
);

foreach($strings as $data){
$pattern = '/\d{2}\.\d{2}(?:\s\d{2}:\d{2})?\s-\s(.*?)(?:\s::|$).*/';
echo preg_replace($pattern, '$1', $data) . "\r\n<br>";
}

It will output:

foobar1 bla bla 
" foobar2 bla bla " 

Upvotes: 2

Related Questions