regex help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sugapablo

    #1

    regex help

    Could someone help me out with a regular expression?

    I need to be able to search a text field and grab every instance of a
    string that falls between <tag class="name"> and </tag>.

    We can assume that the tags will always be written properly.


    So if the following is my text field: "They streamed across the Clemente
    Bridge, docked along the <tag class="name">Al legheny River</tag>, strolled
    from the North Side and biked down the trail to watch their Pirates. <br/>
    They filled <tag class="name">PN C Park</tag> to the last sliver of
    standing-room space on the rotunda, <tag class="name">37 ,259</a> strong.
    <br/> And they came in full throat, chanting and cheering from the outset."

    ....I'd need the code to return, probably an array, like this:
    $array[0] = Allegheny River
    $array[1] = PNC Park
    $array[2] = 37,259


    I just can't get it. Any suggestions?

    --
    [ Sugapablo ]
    [ http://www.sugapablo.net <--personal | http://www.sugapablo.com <--music ]
    [ http://www.2ra.org <--political | http://www.subuse.net <--discuss ]

  • Daniel Tryba

    #2
    Re: regex help

    Sugapablo <russ@removesug apablo.com> wrote:[color=blue]
    > We can assume that the tags will always be written properly.[/color]

    So why did you make an error in your example? :)

    [string][color=blue]
    > ...I'd need the code to return, probably an array, like this:
    > $array[0] = Allegheny River
    > $array[1] = PNC Park
    > $array[2] = 37,259
    >
    >
    > I just can't get it. Any suggestions?[/color]

    Tell us where you are running into problems. It's really simple if:
    -you know the correct function
    -you know your regexpes.

    Do you want to learn how to do it or do you just want the answer of how
    to get an array like:

    Array
    (
    [0] => Array
    (
    [0] => <tag class="name">Al legheny River</tag>
    [1] => <tag class="name">PN C Park</tag>
    [2] => <tag class="name">37 ,259</tag>
    )

    [1] => Array
    (
    [0] => Allegheny River
    [1] => PNC Park
    [2] => 37,259
    )
    )

    If you want to learn see
    http://nl2.php.net/manual/en/functio...-match-all.php (the examples
    contain samples that match your question closely) and
    http://nl2.php.net/manual/en/referen...ern.syntax.php (study
    greedy vs. non greedy)

    The spoiler is below:






















    preg_match_all( '/<tag class="name">(. *?)<\/tag>/',$str,$matches );

    Comment

    Working...