开发者

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 w开发者_Go百科ords:

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.


Try with:

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


<?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()


<?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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜