【问题标题】:Grab word from sentences从句子中抓取单词
【发布时间】:2011-06-09 14:58:14
【问题描述】:

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

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

我要抓住这两个字:

ipsum 坐下

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

【问题讨论】:

  • 是什么让“ipsum”和“sit”特别是它们被“抓住”而不是其他词?
  • 不只是例子。句子将是可变的。用户输入句子然后我会抓住它:)
  • Daniel 之所以这么问,是因为如果不知道您想要捕捉的是什么,就无法提供帮助。字面意思是“ipsum”和“sit”?还是有其他因素?
  • 因子是“”。我应该用这个符号“

标签: php regex


【解决方案1】:

尝试:

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

【讨论】:

  • 我给了我警告:preg_match_all() [function.preg-match-all]: Unknown modifier ']' :(
  • 你不需要让量词变得懒惰,你需要在你的正则表达式周围添加分隔符。
【解决方案2】:
<?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()

【讨论】:

    【解决方案3】:
    <?php
    $subject = "ilorewm ipsum dolor sit amet ";
    $pattern = '/ipsum|sit/';
    preg_match_all($pattern, $subject, $matches);
    print_r($matches);
    ?>
    

    我的答案与其他答案的区别主要在于模式。注意 ipsum|sit。与 ipsum 或 sat 匹配。还要注意 preg_match_all 而不是 preg_match 匹配多次出现,而不仅仅是每行一个。

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

    【讨论】:

      【解决方案4】:

      假设你的意思是你想知道这两个词是否在字符串中,你应该使用 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

      【讨论】:

      • preg_match 显然是完成此任务的一种优越方法,如果您阅读 OP 帖子中的 cmets,您会发现他正在寻找用双引号括起来的任何单词。
      • 糟糕。误解了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多