Page 1 of 1

Replacing an html page title

Posted: Wed Mar 23, 2005 4:25 am
by starsol
I'm sure this is really simple but I just can't find a way to do it:

I have a template file for a website which naturally contains:

<title>website name</title>

What I need to do is change the page title to a product name, and up until now I have simply been using str_replace to change "website name" to "product name". However, now the template file is updated often and not by myself, and the title sometimes get changed. What I'm looking for is some code to find "<title>*anything*</title>" and change it to "<title>product name</title>".

From what I can tell preg_replace is the way to go, but I've not used it before and can't figure out how to apply it here. Can anyone give me a helping hand on this one?

Thanks in advance!

Posted: Wed Mar 23, 2005 4:34 am
by n00b Saibot
why don't you define a variable named $TITLE or something like that in place of hard-coded title in the template and when the template is applied on the product-page, all you have to do is to set the variable $TITLE to the product-name. It will automatically update the title.

Posted: Wed Mar 23, 2005 4:43 am
by Chris Corbyn
Try using a switch.

Example:

Code: Select all

<title>Company Name - <?php

switch ($product) {
    case 'fish_rod': echo 'Fishing Rods';
    break;
    case 'moon_rock': echo 'Moon Rocks';
    break;
    default: echo 'A nice company we are!';
    break;
}
?></title>

Posted: Wed Mar 23, 2005 6:13 am
by starsol
Echoing out a variable isn't an option. What I want is a snippet of code that looks for <title>*anything*</title> in a string and replaces it with a variable.

Like how str_replace works, but allowing for a wildcard in the middle (hope I'm making sense).

Posted: Wed Mar 23, 2005 6:39 am
by Chris Corbyn
I see what you're saying but I'm struggling to see why you need this.. Are you getting the document contents using file_get_contents() or fread() or similar? The RegExp would be something like:

Code: Select all

$title = 'Your product';

$new_document = preg_replace('/<title>(.|\s)*?<\/title>/i', '<title>'.$title.'</title>', $original_document);

Posted: Wed Mar 23, 2005 6:51 am
by starsol
Yep am getting the template file using file_get_contents.

What you posted seems like what I'm looking for - I'll give it a try :D.