Jump to content

Finding text three characters before chosen string


eits

Recommended Posts

Hi, Seasons greetings etc. everybody, I hope you had a good one! I need some help please ;D! I have a html file in a var called $html which I have got using CURL.

 

In this file there is a tag called <beforethis>. And just before this tag is a number (it could be 1 digit or 2).

 

How would I go about searching through $html and finding the number just before the <beforethis> tag?

 

I'd be REALLY greatful if anybody could help, I've tried to explain clearly but if I haven't I'll be willing to elaborate.

 

Many Thanks

 

for 1 or 2 digits it should be

 

<?php
$html = "testing some test 12<beforethis>"
if (preg_match('/(\d{1,2})<beforethis>/sim', $html , $regs))
{
echo "found: ".$regs[1];
}
?>

 

but DarkWater will grab ALL digits.. it depends how exact you want to be, i would probably use DarkWater's  ;)

<?
$html='123<beforethis>test<hh>test</hh>s9<beforethis>';
$arr=explode("<beforethis>",$html);
foreach($arr  as $key=>$value){
$digit=substr($value,strlen($value)-2,2);
$digit=ereg_replace("[^0-9]","",$digit);
if($digit !=""){
print $digit."<br>";
}
}
?>

@omarh:  Just about everything in that code that could go wrong DID go wrong.  You used short tags, you didn't bother indenting, you didn't use the negative length option of substr(), and you used ereg_replace().  It's so much better with a nice, simple regex.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.