Tsukimoto Mitsumasa
Tsukimoto Mitsumasa

Reputation: 582

Using preg_match and str replace to find a word and highlight it

this is my code..

<?php
    // first get all the html contents

    $page = file_get_contents('http://www.planetled.com.au/blog/what-is-a-led-spotlight/');


    //next explode it
    $words = explode(" ", $page);

    // then display the 21st word or any word you like
    echo $words[22]; // 21st word
?>

What I wanted next is to find the 21st human readable word. I'm thinking of using preg_match to find the word and then use str_replace but what I'm missing is what patter will I use in preg_match? Thank you.

Upvotes: 0

Views: 389

Answers (1)

Dean Grell
Dean Grell

Reputation: 143

The problem here is the page you are referencing will return the HTML contents of the site...so it will not be the 21st human readable word...but here's how you can highlight it! I'm not sure on the double declaration of $words[20] inside the str_replace, but it works. Someone will chime in with a correction...

str_replace($words[20], "<span style='background-color:yellow'>$words[20]</span>", $words[20]); 

Upvotes: 1

Related Questions