array/loop performance improvement?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cathalmccabe
Forum Newbie
Posts: 1
Joined: Tue Jul 08, 2008 4:13 am

array/loop performance improvement?

Post by cathalmccabe »

Hello,
I want to read a page, and copy a line of html from it. I want to strip out hyperlinks in the line, so I am starting the loop at a particular point on the line, then checking each 2 characters for "<a".
If I find a link, I ignore the text (until I find ">").

The performance of this code is not good enough as it times out. (Fatal error: Maximum execution time of 30 seconds exceeded in ...)
I can't increase the time.

I have no feel for how long something like this should take. Is the loop too big? Are there any obvious ways to improve performance?

Is there a better way of doing what I am attempting?

Thanks in advance.

Code: Select all

<?php
$lines = file('...');
 
$ignore = 0;
 
// Print each required character, checking for hyperlinks <a and ignoring the link
for ( $counter = 360; counter <= 3380; $counter += 1) {
  if($lines[135][$counter] == "<" && $lines[135][$counter+1] =="a"){
    // check for <a
      $ignore = 1;
  }
  
  if($ignore == 0){
    echo  $lines[135][$counter];
  }else if($lines[135][$counter] == ">"){
  // check for end of ignore
    $ignore = 0;
  }
}
?>
 
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: array/loop performance improvement?

Post by Eran »

check this site for loop optimizations in php - http://www.phpbench.com/
dml
Forum Contributor
Posts: 133
Joined: Sat Jan 26, 2008 2:20 pm

Re: array/loop performance improvement?

Post by dml »

Code: Select all

for ( $counter = 360; /*XXX*/counter <= 3380; $counter += 1) {
That could be an infinite loop. Try:

Code: Select all

for ( $counter = 360; $counter <= 3380; $counter += 1) {
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: array/loop performance improvement?

Post by Christopher »

You may want to look into using preg_match instead. I will probably be faster than looping like you are.
(#10850)
Post Reply