Elbek
Elbek

Reputation: 3484

Grab word from sentences

I want to grab words from sentences in PHP, for example in the following sentence:

lorewm "ipsum" dolor "sit" amet ...

I want to grab these two words:

ipsum sit

The sentences can be any length, I just want to grab all of the words surrounded by quotes (""). Regex may be one acceptable way to do this.

Upvotes: 0

Views: 207

Answers (4)

matchew
matchew

Reputation: 19645

<?php
$subject = "ilorewm ipsum dolor sit amet ";
$pattern = '/ipsum|sit/';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>

the difference between my answer and the others is largely the pattern. Note the ipsum|sit. which matches either ipsum OR sit. also notice preg_match_all and not preg_match to match multiple occurrences, not just one per line.

note: http://php.net/manual/en/function.preg-match-all.php

Upvotes: 1

Jeremy
Jeremy

Reputation: 5435

Assuming what you mean is that you want to know if those two words are in the string, you should use PHP's strpos function. On some other languages, you'd use indexOf -- both methods return false/null/a negative number if the string isn't found.

In PHP, you'd do:

<?php
$pos = strpos($fullsentence,$word);

if($pos === false) {
  // the word isn't in the sentence
}
else {
  //the word is in the sentence, and $pos is the index of the first occurrence of it
}
?>

More info: http://www.maxi-pedia.com/string+contains+substring+PHP

Upvotes: -1

hsz
hsz

Reputation: 152216

Try with:

$input = 'lorewm "ipsum" dolor "sit" amet';
preg_match_all('/"([^"]*)"/', $input, $matches);

Upvotes: 4

Gerben Jacobs
Gerben Jacobs

Reputation: 4583

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

http://php.net/manual/en/function.preg-match.php

And in your case preg_match_all()

Upvotes: 1

Related Questions