Web Analytics Made Easy -
StatCounter Help needed with a preg_match script - CodingForum

Announcement

Collapse
No announcement yet.

Help needed with a preg_match script

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help needed with a preg_match script

    Hi,

    My database contains the following text:
    The voice of the Public, like the voice of an oracle, it
    becomes an Author to hear with respectful silence. Even while it
    mortifies, it instructs; while it refuses approbation, it teaches
    wisdom. It checks ambition in its wild career; and reminds the
    candidate for fame to return into that deceiving path of life, from
    which he ought not to have deviated, and which, how mortifying
    soever to the Author, is perhaps the happiest for the Man.
    If need to write a script that returns a sentence where the keyword is exists.
    For example, if I search for "voice", it should ECHO me:
    The voice of the Public, like the voice of an oracle, it
    becomes an Author to hear with respectful silence.
    The whole sentence, ends with dot . or shouting ! or wiht question mark ?.....

    But if I search for "author", it should ECHO me:
    The voice of the Public, like the voice of an oracle, it
    becomes an Author to hear with respectful silence.
    It checks ambition in its wild career; and reminds the
    candidate for fame to return into that deceiving path of life, from
    which he ought not to have deviated, and which, how mortifying
    soever to the Author, is perhaps the happiest for the Man.
    So do you see that it should ECHO two sentences because two sentences has the word "author". This is what I have made so far:
    PHP Code:
    $return "";
    preg_match("/.*$search.*/i",$text,$return);
    echo 
    $return[0]; 
    This is not very good yet. It ECHOS just the line not sentence and it only ECHOES the first match, it should keep echoing all matches.

    Any help? Much appreciated!
    PHP 5 & MySQL 5 (Y)

  • #2
    preg_match_all() might serve you better than preg_match().

    I would explode the paragraph (which separates each sentence into its own array index) and then do a strpos() on each array element. Probably because I'm not entirely comfortable with regexes yet.

    Comment


    • #3
      My code is now:

      PHP Code:
      $count preg_match_all("/.*$search.*/i",$text,$matches);
      foreach (
      $matches as $key)
       {
        for (
      $b 0;$b $count;$b++)
         echo 
      "RESULT: ".$key[$b]."<br /><br />\n";
       } 
      But I would still need it to echo only the sentence not line! :/

      Any help?
      PHP 5 & MySQL 5 (Y)

      Comment

      Working...
      X