0

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.

Tsukimoto Mitsumasa
  • 541
  • 4
  • 19
  • 42
  • 1
    The 21st word is at index 20, not 22 –  Aug 07 '12 at 14:27
  • Well can you be sure the page being loaded is literally just a list of words, or is there other content in there? If so, your `explode` will be compromised. Also, the 21st key of an array is `$arr[20]`, not 21 (since 0 is the first). – Mitya Aug 07 '12 at 14:27
  • this could help : http://stackoverflow.com/questions/9304212/sed-replacing-nth-word-with-matched-pattern – mlishn Aug 07 '12 at 14:28
  • 1
    I don't understand why you would need regular expression to find the word, when you have already broken up the array of words and simply need to access the word at index = 20 – Mike Brant Aug 07 '12 at 14:28
  • If you want to filter out html tags, please, please, please [forget about regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454), just parse the document! – Elias Van Ootegem Aug 07 '12 at 14:46

1 Answers1

1

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]); 
Dean Grell
  • 143
  • 8
  • 1
    Not quite - the parameters for str_replace are search,replace,subject, so it would need to be `str_replace($words[20],'text',$words[20])` – Dennis Hackethal Aug 07 '12 at 14:53
  • 1
    For some functions the parameters can be in different order. E.g. [here](http://de2.php.net/manual/en/function.implode.php) you will find that "implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments." Could not find the same for str_replace, but it might be the same reason. – Dennis Hackethal Aug 07 '12 at 15:06