【问题标题】:php: How to find a string in a paragraphphp:如何在段落中查找字符串
【发布时间】:2013-05-31 07:00:29
【问题描述】:

假设我有:

$strPar = "This is a simple paragraph that we will use for the questioning";
$strFindMe = "that";

如何检查$strPar 是否包含$strFindMe

【问题讨论】:

标签: php string variables character


【解决方案1】:

最快的方法是使用strpos:

  $exists = strpos($strPar, $strFindMe);
  if ($exists !== false) {
    // substring is in the main string
  }

【讨论】:

  • @BartFriederichs 是否必须使用!== false
  • 先生,另一个问题,我如何用“|”替换新行
【解决方案2】:

试试这样的

if (false !== strpos($strPar, $strFindMe ) )

【讨论】:

  • 为什么你需要false !== ,因为它返回布尔值?
  • 它返回的位置,如果它在字符串的开头将是0,这将评估为假。
【解决方案3】:
$string = "This is a strpos() test";
$pos = strpos($string, "i", 3);

    if ($pos === false) {
     print "Not found\n";
}else{
     print "Found at $pos!\n";
}

【讨论】:

    【解决方案4】:
    <?php
    $strPar = "This is a simple paragraph that we will use for the questioning";
    $strFindMe   = "that";
    $pos = strpos($strPar, $strFindMe);
    
    // Note our use of ===.  Simply == would not work as expected
    // because the position of 'a' was the 0th (first) character.
    if ($pos === false) {
        echo "The string '$findme' was not found in the string '$mystring'";
    } else {
        echo "The string '$findme' was found in the string '$mystring'";
        echo " and exists at position $pos";
    }
    ?>
    

    【讨论】:

      【解决方案5】:

      检查strpos()函数,区分大小写!

      if( strpos($strPar, $strFindMe) ) {  //it return a boolean value
         echo "String Found";
      }
      

      【讨论】:

        【解决方案6】:
        $strPar = "This is a simple paragraph that we will use for the questioning";
        $strFindMe = "THAT";//Find the position of the first occurrence of a case-insensitive substring in a string
        $exists = strpos($strPar, $strFindMe);
          if ($exists !== false) {
            // substring is in the main string
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-22
          • 2021-03-30
          • 2011-08-11
          • 2021-06-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-23
          • 1970-01-01
          相关资源
          最近更新 更多