PDA

View Full Version : PHP help please!



themoose
February 23rd, 2006, 12:48
I'm trying to get a script to read each line of a file, get the text between the <b> tags and echo it. So far I've got this but it doesnt really work:


<?php
function getBetween($str, $start, $end) {
$startlen = strlen($start);
if (($startpos = strpos($str, $start)) !== false
&& ($endpos = strpos($str, $end)) !== false
&& ($skip = $startpos + $startlen) <= $endpos) {
return substr($str, $skip, $endpos - $skip);
} else {
return false;
}
}

$lines = file("file.html");
$start = "<b>";
$end = "</b>";

foreach($lines as $line) {
if(($echo = getBetween($line, $start, $end)) !== false) {
echo $echo;
} else {
echo "Not Found";
}
}
?>

(I do not take credit for all of this code. I found most of it googling :))

It keeps on echoing Not Found, whatever I do. Please can somebody help me?

Thanks,

tm

Richard
February 23rd, 2006, 13:13
Use the php explode function while reading the whole file, then read line by line.

http://uk.php.net/manual/en/function.explode.php

Something like this:


// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

themoose
February 23rd, 2006, 13:29
I dont understand

Richard
February 23rd, 2006, 13:54
I dont understand

Use the explode function to seperate the html into 3 parts.

1) The part before the <b> tag,
2) The part in the middle of the <b> and the </b>
3) The part after the </b> tag


$data = "<html>This is the data<b>right</b> here";
list($before, $data2) = explode("<b>", $data);
// $data2 stores all data after the <b> tag
list($middle, $after = explode("</b>", $data2);

// $middle stores the text in the middle of the <b> and </b> tags
// This is an example, may not work, it's untested!

themoose
February 23rd, 2006, 14:14
doesnt work at all, lol (even after a few error mistakes :P). And yes, I did echo $middle.

themoose
February 23rd, 2006, 15:30
I've got it, thanks guys.


$file = file_get_contents("file.html");
preg_match_all("/<B>(.*?)<\/B>/si", $file, $matches, PREG_PATTERN_ORDER);

foreach($matches[0] as $match)
{
echo $match.'<br />';
}


from help from another forum :)

Richard
February 23rd, 2006, 17:24
Well. A bit of a touch up on the explode function using an array would of got it to work. But yeah, that code's good :P

DarkBlood
February 23rd, 2006, 22:03
As TM has figured it out. Explode function is useful for when splitting up variables that are spaced with such a thing as / ? & \ or | stuff. Fortunately for TM, he found out about the preg and ereg stuff... these two (series) functions allow you to search AND replace a STRING and not just variables between markers.