Posts Tagged ‘file_get_contents’

Highlight String in PHP

Posted 23 Jan 2010 — by admin
Category php

Function for highlighting text/strings in PHP.

$content = file_get_contents("http://php.net/");

print highlight("PHP", $content);

function highlight($match, $string){
  return str_ireplace($match, "<span style='background:yellow'>$match</span>", $string);
}

Will output something like this

Highlighted PHP.Net

Highlighted PHP.Net

***Notice all the styles are gone :( … would need to parse the document body to maintain stylesheet and other ‘php’ strings that might be in resources paths.

Absolutize Relative Links Using PHP and Preg_Replace_Callback

Posted 13 Jan 2010 — by admin
Category php

I was in the market for a simple php script to replace hrefs with their absolute paths from scraped web pages. I wrote one myself. I used the preg_replace_callback function so that I could pass the parsed results as a single variable.

<?php
$domain = "http://seanbehan.com";
$pattern = "/\bhref=[\"|'](.*?)[\"|']/";
$string = file_get_contents($domain);

// prepends relative links w/ $domain skips returns the match if already absolute
function replace_href($match){
  global $domain;
  if(substr($match[1], 0, 7)!=="http://" && substr($match[1],0,8)!=="https://"){
    return "href='".$domain.$match[1]."'";
  } else {
    return "href='".$match[1]."'s";
  }
}
print preg_replace_callback($pattern, "replace_href", $string);