略过具有确定第一个单词的句子

时间:2012-10-29 22:46:58

标签: php

我想检查一些句子的第一个单词。如果第一个字是ForAndNorButOr等,我想跳过这句话。

以下是代码:

<?php
  $sentence = 'For me more';
  $arr = explode(' ',trim($sentence));
  if(stripos($arr[0],'for') or stripos($arr[0],'but') or stripos($arr[0],'it')){
    //doing something
  }
?>

空白结果,什么错了?谢谢你:))

3 个答案:

答案 0 :(得分:2)

此处,如果找到该单词,stripos将返回0(在位置0处找到)。

如果找不到单词,则返回false。

你应该写:

if(stripos($arr[0],'for') !== false or stripos($arr[0],'but') !== false or stripos($arr[0],'it') !== false){ 
  //skip 
}

答案 1 :(得分:2)

Stripos返回大海捞针第一次出现时的位置 第一次出现在位置0,其评估为假。

尝试将此作为替代

$sentence = 'For me more';

// make all words lowercase
$arr = explode(' ', strtolower(trim($sentence)));

if(in_array($arr[0], array('for', 'but', 'it'))) {
   //doing something
   echo "found: $sentence";
} else {
   echo 'failed';
}

答案 2 :(得分:2)

如果您想知道要评估的字符串是什么(也就是说您不需要解析句子),也许可以使用preg_filter

$filter_array = array(
    '/^for\s/i',
    '/^and\s/i',
    '/^nor\s/i',
    // etc.
}

$sentence = 'For me more';

$result = preg_filter(trim($sentence), '', $filter_array);

if ($result === null) {
    // this sentence did not match the filters
}

这允许您确定一组过滤器正则表达式模式,以查看您是否匹配。请注意,在这种情况下,我只使用''作为“替换”值,因为您并不真正关心实际进行替换,这个函数只是为您提供了一个很好的方法来表达正则表达式数组。 / p>