Page 1 of 1

Get HTML TAG once

Posted: Mon Oct 24, 2005 8:59 am
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;

Posted: Mon Oct 24, 2005 11:41 am
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 ;)