split string that start with .. and end with ..

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

split string that start with .. and end with ..

Post by yacahuma »

Need to split a string that contains something like

<b>10-10-2005 Radio 1</b>TEXTHERETEXTHERETEXTHERETEXTHERETEXTHERETEXTHERE<b>10-12-2005 Radio 1</b>TEXTHERETEXTHERETEXTHERETEXTHERETEXTHERETEXTHERE

What I want at the end is an array like
[1]10-10-2005
[2]10-12-2005

Thank you
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: split string that start with .. and end with ..

Post by prometheuzz »

Code: Select all

<?php
if(preg_match_all(
    '/\d?\d-\d?\d-\d{4}/', 
    '<b>10-10-2005 Radio 1</b>TEXTHERETEXTHERETEXTHERETEXTHERETEXTHERETEXTHERE
     <b>10-12-2005 Radio 1</b>TEXTHERETEXTHERETEXTHERETEXTHERETEXTHERETEXTHERE',
    $matches)) {
  print_r($matches);
}
?>
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: split string that start with .. and end with ..

Post by GeertDD »

Prometheuzz's regex will do the job. However, what if the "textheretexthere" part contained a date as well? It would get matched too. I suggest to slightly alert the regex to provide an extra hook to the preceding <b>.

Code: Select all

Before:          \d?\d-\d?\d-\d{4}
After:   (?<=<b>)\d?\d-\d?\d-\d{4}
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: split string that start with .. and end with ..

Post by yacahuma »

Thank you all. This works.
Post Reply