从句子中抓取单词

时间:2011-06-09 14:58:15

标签: php regex

我想从PHP中的句子中获取单词,例如在下面的句子中:

  

lorewm“ipsum”dolor“坐”amet ...

我想抓住这两个词:

  

存有   坐

句子可以是任意长度,我只想抓住所有被引号括起来的单词("")。正则表达式可能是一种可接受的方式。

4 个答案:

答案 0 :(得分:4)

尝试:

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

答案 1 :(得分:1)

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

在你的情况下preg_match_all()

答案 2 :(得分:1)

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

我的答案和其他答案之间的差异主要是模式。注意ipsum | sit。哪个匹配ipsum或坐。还要注意preg_match_all而不是preg_match来匹配多次出现,而不是每行一次。

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

答案 3 :(得分:-1)

假设你想知道这两个单词是否在字符串中,你应该使用PHP的strpos函数。在其他一些语言中,你使用indexOf - 如果找不到字符串,两个方法都返回false / null /一个负数。

在PHP中,您可以:

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

更多信息: http://www.maxi-pedia.com/string+contains+substring+PHP