【问题标题】:How to check if string contains excactly 2 substrings如何检查字符串是否正好包含 2 个子字符串
【发布时间】:2017-10-11 20:17:28
【问题描述】:
$string = "/*123123123*/";
$string = "123/*123123*/";
$string = "/*123123*/123";
$string = "123/*123123*/123";

对于所有这些变体,我需要返回 true,因此 /* 和 */ 存在于字符串中。

试过

if(preg_match("/(/*&*/)/i", $string)){ 

          $flag=true;
       }
       else{
           $flag=false;
       }

但没有成功:c

【问题讨论】:

  • 只要使用strpos

标签: php string boolean substring


【解决方案1】:

使用 substr_count():http://php.net/manual/en/function.substr-count.php

int substr_count (string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

【讨论】:

    【解决方案2】:

    你可以使用:

    if (preg_match('%/\*.+\*/%', $string)) {
        $flag = true;
    } else {
        $flag = false;
    }
    

    Regex Demo and Explanation

    【讨论】:

    • 请看我的回答(:
    • 应该变得懒惰.+? 否则它会吓坏像 `/* comment / code / comment */ 这样的事情,除非它真的只是关于如果两者都在
    【解决方案3】:

    我用过

    if((strpos($string,"/*")!== FALSE) && (strpos($string,"*/")!== FALSE)){
               $flag=true;
           }
           else{
              $flag=false;
           }
    

    实际上不知道什么更好用,上面的代码,或者 Pedro Lobito 的正则表达式代码:

    if (preg_match('%/\*.+\*/%', $string)) {
        $flag = true;
    } else {
        $flag = false;
    }
    

    【讨论】:

    • 哪种效果更好完全取决于您。除非您编写一些访问量很大的代码,否则我不会太担心什么性能更好。这两者都应该及时执行。如果你在几周、几个月甚至几年后回顾它,专注于你更容易理解的事情。个人 id pic opt #1 因为它比正则表达式更容易阅读(尽管这个非常简单)
    • 另外,如果你真的想节省空间,你可以使用 $flag = (strpos($string,"/*")!== FALSE) && (strpos($string,"*/")!== FALSE); 这样的东西,因为它会像在 if 中一样返回 true 或 false
    猜你喜欢
    • 2011-11-09
    • 2013-05-18
    • 1970-01-01
    • 2021-12-20
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2013-02-05
    相关资源
    最近更新 更多