Home > other >  How to get Sentence From Long String which contains specific Word using PHP
How to get Sentence From Long String which contains specific Word using PHP

Time:02-10

I know How to check if a string contains a specific word

if (str_contains('How are you', 'are')) { 
    echo 'true';
}

But I am looking for give search result like below to my users

enter image description here

so if my string is like below

Paragraph development begins with the formulation of the controlling idea. This idea directs the paragraph’s development. Often, the controlling idea of a paragraph will appear in the form of a topic sentence. In some cases, you may need more than one sentence to express a paragraph’s controlling idea.

and then if my user search with word like idea directs then I want show result like This idea directs the paragraph’s development

I do not have idea which PHP function can help me for achieve my goal. Let me know if anyone here can help me for achieve my goal. Thanks!

CodePudding user response:

There is no simple function to achieve this directly. You will have to write an algorithm to get it done. Something similar below.

$text = "Paragraph development begins with the formulation of the controlling idea. This idea directs the paragraph’s development. Often, the controlling idea of a paragraph will appear in the form of a topic sentence. In some cases, you may need more than one sentence to express a paragraph’s controlling idea.";
$search = "idea directs";
$sentenses = explode(".", $text);

for($i = 0; i < sizeof($sentenses); $i  ){
    if(strpos($sentenses[$i], $search))
        echo $sentenses[$i];    
}

convert the text into lowercase will help you to search case-insensitive,

  •  Tags:  
  • Related