0

I have a HTML file, which contains many href="", src="" attributes, and I need to use PHP to read in the whole HTML file, then use PHP code to replace all the value of href="", src="" to the ones I want. I think the steps are:

  1. use file_get_contents() to read the abc.html file and save it into a variable
  2. About the href="", src="" value replacing part, is it better to use string replace functions or use regular expression?
  3. echo the final variable(the updated HTML).
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
NeoGeo
  • 49
  • 1
  • 6
  • 1
    Use Simple PHP HTML DOM http://simplehtmldom.sourceforge.net/ – Makesh May 19 '15 at 06:39
  • str_replace will be faster, but depends on how complicated your replacement is. Replacing href="mypage.php" to href="/newdir/mypage.php" is easy, but href="/one-of-a-number-of-directories/mypage.php" would be for regexes. You might find using PHP to insert a base href tag would achieve the result you're looking for too. – wrightee May 19 '15 at 06:43

2 Answers2

-1

I'd use MVC model and renderer functions. For example: index.php

<!DOCTYPE HTML>
<html>
    <head>
        <title><?=$title; ?></title>
    </head>
    <body>
        <h3><?=$text; ?></h3>
    </body>
</html>

Than I'll have PHP array that contains those variables:

$array = array("title"=>"Mypage", "text"=>"Mytext");

Now we will use both in renderer function

function renderer($path, $array)
{
    extract($array);
    include_once("$path.php");
} 
renderer("index", $array);
David Demetradze
  • 1,361
  • 2
  • 12
  • 18
-1
define('TEMPLATE', __DIR__ . DIRECTORY_SEPARATOR . 'index.html');

$template = file_get_contents(TEMPLATE);

$patterns = array();
$patterns[0] = '/href="(.{0,})"/';
$patterns[1] = '/src="(.{0,})"/';

$replacements = array();
$replacements[0] = 'href="link"';
$replacements[1] = 'src="src"';


$template = preg_replace($patterns, $replacements, $template);

echo $template;

File index.html currently on same directory with PHP script. You can specify path to file modifying constant. In paterns/replacement array you can add any other paterns

Oleg
  • 655
  • 4
  • 10