Frantisek
Frantisek

Reputation: 7693

How do I return a part of text with a certain word in the middle?

If this is the input string:

$input = 'In biology (botany), a "fruit" is a part of a flowering plant that derives from specific tissues of the flower, mainly one or more ovaries. Taken strictly, this definition excludes many structures that are "fruits" in the common sense of the term, such as those produced by non-flowering plants';

And now I want to perform a search on the word tissues and consequently return only a part of the string, defined by where the result is, like this:

$output = '... of a flowering plant that derives from specific tissues of the flower, mainly one or more ovaries ...';

The search term may be in the middle.

How do I perform the aforementioned?

Upvotes: 1

Views: 54

Answers (2)

daiscog
daiscog

Reputation: 12057

An alternative to my other answer using preg_match:

$word = 'tissues'

$matches = array();

$found = preg_match("/\b(.{0,30}$word.{0,30})\b/i", $string, $matches);

if ($found == 0) {
    // string not found
} else {

    $output = $matches[1];

}

This may be better as it uses word boundaries.

EDIT: To surround the search term with a tag, you'll need to slightly alter the regex. This should do it:

$word = 'tissues'

$matches = array();

$found = preg_match("/\b(.{0,30})$word(.{0,30})\b/i", $string, $matches);

if ($found == 0) {
    // string not found
} else {

    $output = $matches[1] . "<strong>$word</strong>" . $matches[2];

}

Upvotes: 3

daiscog
daiscog

Reputation: 12057

User strpos to find the location of the word and substr to extract the quote. For example:

$word = 'tissues'

$pos = strpos($string, $word);

if ($pos === FALSE) {
    // string not found
} else {

    $start = $pos - 30;
    if ($start < 0)
        $start = 0;


    $output = substr($string, $start, 70);

}

Use stripos for case insensitive search.

Upvotes: 1

Related Questions