Jump to content

Extracting text from a string


debbie-g85

Recommended Posts

I have managed to get this to work but it seems like it is a very long and messy solution. I was wondering if anyone had an idea of how this can be done better. I am new to php and don't know a lot.

 

It shows the text between the tags <h1> and </h1> from the content of a different file

Basically I had to start the substr() from the fourth position so it would actually skip the "<h1>" being included, and because I started on the fourth postion I then had to finish four places back to skip the "</h1>" being included. 

 

<?php
$id = $_GET['id'];
$homepage = file_get_contents("./".$id.".php");
$title = stristr($homepage,"<h1>");
$titlepos = strpos($homepage,"</h1>");
$endpos = $titlepos - 4;
echo "Title " . substr($title,4,$endpos);

?>

Link to comment
https://forums.phpfreaks.com/topic/235215-extracting-text-from-a-string/
Share on other sites

You could go the regex approach which is alot more cleaner

$homepage = file_get_contents("./".$id.".php");
preg_match_all('/<h1>(.*?)<\/h1>/i', $homepage, $matches);
echo "<pre>".print_r($matches[1], true)."</pre>";

 

$matches[1] will return an array of h1 headings it finds (without the <h1> and </h1> tags).

From the example she gave in post #1 it's the text between the <h1> tags she's looking for.

Which is what my code does. It grabs the text between the <h1> and </h1> for each heading it finds.

 

For example, if $homepage is set to

<h1>one</h1>

text blah

<h1>test123</h1>

boob

 

Then the outut of my script will be

Array
(
    [0] => one
    [1] => test123
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.