Get HTML TAG once

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

Moderator: General Moderators

Post Reply
wooozy
Forum Newbie
Posts: 1
Joined: Mon Oct 24, 2005 8:52 am

Get HTML TAG once

Post by wooozy »

I have a string like this:

$str = "<tbody>more tags A</tbody>
<tbody>more tags B</tbody>
<tbody>more tags C</tbody>
<tbody>more tags D</tbody>";



Then i want to use reg ex to only get the first <tbody>more tags A</tbody>. How do i do that?

I have tried these regular expressions:
-----------------------------------------------------
eregi("(<tbody[^>]*>(.*)</tbody>){1}", $str, $tBodys); // <-- you get all tbodys, but it should be only once, look at {1}

eregi("(<tbody[^>]*>(.*)</tbody>)", $str, $tBodys); // <-- you get all tbodys


$tBody = $tBodys[0];
echo $tBody;
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Code: Select all

$str = "<tbody>more tags A</tbody>
<tbody>more tags B</tbody>
<tbody>more tags C</tbody>
<tbody>more tags D</tbody>"; 

preg_match('@<tbody>((?:.(?!</tbody>))*.)</tbody>@is', $str, $matches);

print_r($matches);
Untested but it's just:

Find <tbody>
(?:.(?!</tbody>))* ==> Find anything not followed by </tbody> any number of times (not extracted)
. ==> The last character before </tbody>

The other parens cause the last two of the above to be extracted.

Let me know if ti work ;)
Post Reply