Read contents of a file

A

Anonymous

Guest
Hi,

I have a simple question.
Heres my code:
Code:
<?php

$filename  = "testfile.php";
$contents = file_get_contents($filename);

if (preg_match('~<title>(.*?)</title>~', $contents, $title))
{
	$text = implode(" ",$title);
	echo strip_tags($text);
}


?>

This is the file:
Code:
<html>
<title>Testfile</title>

<body >

<h3><b>This is the headline</b></h3>
<p>And this is some text</p>

</body>
</html>

The code works, however the output (Title) is displayed twice.
Any suggestions to why?

Heres the output:
Testfile Testfile
 
Even though it's a "simple" question it is confusing to me what you are after. Especially when you say the code works, but it displays it twice?

Sorry stupid me didn't see your whole post.
 
$title is an array, not a string.

The reason you see the text twice is that the first item in the array is the text with the title tag and the second item is the title text itself.

Have a look :

Code:
<?php
$filename  = "testfile.php";
$contents = file_get_contents($filename);
if ( preg_match( '/<title>(.*?)<\/title>/', $contents, $title ) )
{
	echo '<pre>' . htmlentities( print_r( $title, TRUE ) ) . '</pre>';
	echo '<p>' . htmlentities( $title[0] ) . '</p>';
	echo '<p>' . $title[1] . '</p>';
}
?>

Live Regex test here :
https://www.phpliveregex.com/#tab-preg-match
 
Back
Top