I've been coding php for about four years now on and off. I'm attempting to write a script that will replace links on a page with another link. I'm debating whether it's even worth it to try to code something with strpos. I was of the opinion that preg_match would be slower, but I'm not so sure anymore. The logic with my script seems to be flawed. Man I hate working with strings.

$buf = '<a href="http://www.google.com"><a href="http://www.google.com">';

replace_urls($buf);


function replace_urls(&$file) { 
                                     // is string length
	$elem['src='] 		= 4;
	$elem['background=']= 11;
	$elem['href='] 		= 5;
	$elem['url\('] 		= 5;
	$elem['codebase='] 	= 9;
	$elem['url=']		= 4;
	$elem['archive=']	= 8;
	


	$before = 0;
	$pos = NULL;
    


	  while (list($find,$len) = each($elem) ) {
		
		$offset = 0;
		
	  	while ( $pos <= strlen($file) && ($pos = strpos($file,$find,$offset)) !== FALSE  ) {
	  		
	  		
	  		
	  		//now we are on " or '
	  		$pos += $len;
	  		
	
			//now we are on a char
			$string_start = $pos + 1;
			
			

		
		
			if (  $file{$pos} == '"' ) {  
			$quote = '"'; 
			}  else if ( $file{$pos} == '\'' ) {  
			$quote ='\'';
			} else { 	
			echo 'error'; 
			continue; 
			} 
			
				
			//now we've moved on to string
			$pos++;
			
			
			$findReferencePoint;
	 
	  		while ( $file{$pos} != $quote )
	  					$pos++;
		
				$findReferencePoint = $pos;
	
	  		//if ( ($end - $before) == 0)
	  			//continue;
	  		
	  		
	  		
	  		$url = substr($file,$string_start,$pos-$string_start);
	  		$n_url = 'index.php?r='.$url;		
			$start = substr($file,0,$string_start);
	  		$len = strlen($start) + strlen($n_url);
	  		$file = $start . $n_url . substr($file,$findReferencePoint,strlen($file));
				
			$offset = $len + 1;
			
		
			
			

	  		

	  	}
	  
	  }  


}

If you need to use preg_match() then use it. If strpos() can do the job, then use that. Does that answer your question? Your question wasn't really clear in your post.

I benchmarked my script versus preg_match. My script was slower. I need to process the html of a page and I need to do it fast. I'm just looking for a faster way.

This article has been dead for over six months. Start a new discussion instead.