PHP:如何正确使用Strpos()在字符串中查找单词

时间:2017-06-13 22:36:38

标签: php string strpos

如果一个人有PHP经验,那么就知道如何使用正则表达式和preg_match()或preg_match_all查找字符串中的整个单词及其位置。但是,如果您正在寻找更轻松的解决方案,那么您可能会尝试使用strpos()。问题出现在如何使用这个函数而不检测其他单词中包含的子串。例如,如何检测"任何"但不是"公司"?

中出现的那些人物

考虑如下字符串:

"Will *any* company do *any* job, (are there any)?"

如何使用strpos()来检测"任何"的每个外观?在字符串?现实生活中不仅仅涉及空格分隔的单词。不幸的是,当我最初发布时,这句话并没有出现在非字母字符中。

3 个答案:

答案 0 :(得分:1)

我想你可能只是删除你关心的所有空白字符(例如,连字符怎么样?)并测试" word "

var_dump(firstWordPosition('Will company any do any job, (are there any)?', 'any'));
var_dump(firstWordPosition('Will *any* company do *any* job, (are there any)?', 'any'));

function firstWordPosition($str, $word) {
    // There are others, maybe also pass this in or array_merge() for more control.
    $nonchars = ["'",'"','.',',','!','?','(',')','^','$','#','\n','\r\n','\t',];
    // You could also do a strpos() with an if and another argument passed in.
    // Note that we're padding the $str to with spaces to match begin/end.
    $pos = stripos(str_replace($nonchars, ' ', " $str "), " $word ");

    // Have to account for the for-space on " $str ".
    return $pos ? $pos - 1: false;
}

给出12(偏离0)

https://3v4l.org/qh9Rb

答案 1 :(得分:0)

<?php
$subject = "any";
$b = " ";
$delimited = "$b$subject$b";

$replace = array("?","*","(",")",",",".");
$str = "Will *any* company do *any* job, (are there any)?";
echo "\nThe string: \"$str\"";

$temp = str_replace($replace,$b,$str);
while ( ($pos = strpos($temp,$delimited)) !== false )
{
    echo "\nThe subject \"$subject\" occurs at position ",($pos + 1);
    for ($i=0,$max=$pos + 1 + strlen($subject); $i <= $max; $i++) {
        $temp[$i] = $b;
    }
}

请参阅demo

脚本将单词边界定义为空格。如果字符串具有非字母字符,则将其替换为空格,结果存储在$temp中。当循环迭代并检测$subject时,其每个字符都会变为空格,以便找到主题的下一个外观。考虑到所涉及的工作量,人们可能想知道与使用具有preg_函数的正则表达式相比,这样的努力是否真的得到了回报。这是人们必须自己决定的事情。我的目的是展示如何使用strpos(),而不是诉诸于SO的重复传统智慧,主张使用正则表达式。

如果您不想创建非字母字符的替换数组,可以选择以下选项:

<?php

function getAllWholeWordPos($s,$word){
  $b = " ";
  $delimited = "$b$word$b";
  $retval = false;

  for ($i=0, $max = strlen( $s ); $i < $max; $i++) {
          if ( !ctype_alpha( $s[$i] ) ){
              $s[$i] = $b;
          }
  }

 while ( ( $pos = stripos( $s, $delimited) ) !== false ) {
    $retval[] = $pos + 1;
    for ( $i=0, $max = $pos + 1 + strlen( $word ); $i <= $max; $i++) {
        $s[$i] = $b;
    }
 }
 return $retval;
}

$whole_word = "any";    
$str = "Will *$whole_word* company do *$whole_word* job, (are there $whole_word)?";

echo "\nString: \"$str\""; 

$result = getAllWholeWordPos( $str, $whole_word );
$times = count( $result );
echo "\n\nThe word \"$whole_word\" occurs $times times:\n";
foreach ($result as $pos) { 
   echo "\nPosition: ",$pos;
}

请参阅demo

注意,这个带有更新的示例通过提供一个使用strpos()变体的函数来改进代码,即stripos(),它具有不区分大小写的额外好处。尽管编码更加劳动密集,但性能却很快;见performance

答案 2 :(得分:-2)

尝试以下代码

<!DOCTYPE html>
<html>
<body>

<?php
echo strpos("I love php, I love php     too!","php");
?> 

</body>
</html>


Output: 7