Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:检查字符串是否多次包含相同的单词_Php - Fatal编程技术网

PHP:检查字符串是否多次包含相同的单词

PHP:检查字符串是否多次包含相同的单词,php,Php,我必须多次检查字符串是否包含http或https 例如: https://plus.google.com/share?url=https://example.com/test/ 也可以是: https://plus.google.com/share?url=http://example.com/test/ http和https可以混合使用,因为如果字符串包含“https”,那么它也包含“http”,您可以直接计算“http”的出现次数,例如使用以下函数: 您可以使用preg\u match\

我必须多次检查字符串是否包含http或https

例如:

https://plus.google.com/share?url=https://example.com/test/
也可以是:

https://plus.google.com/share?url=http://example.com/test/

http
https
可以混合使用,因为如果字符串包含“https”,那么它也包含“http”,您可以直接计算“http”的出现次数,例如使用以下函数:


您可以使用
preg\u match\u all()
返回找到的匹配数

if (preg_match_all('/http|https/', $searchString) > 1) {
    print 'More than one match found.';
}

您可以使用正则表达式搜索http和https:

您可以使用。
strpos返回子字符串在字符串中第一次出现的位置。
要查找所有重复调用strpos的实例,请将最后一次strpos调用的返回值+子字符串的长度作为偏移量传递

 function countOccurences($haystack,$needle) {
    $count = 0;
    $offset = 0;
    while(($pos = strpos($haystack,$needle,$offset)) !== FALSE) {
        $count++;
        $offset = $pos + strlen($needle);
        if($offset >= strlen($haystack)) {
            break;
        }
    }
    return $count;
 }

echo countOccurences("https://plus.google.com/share?url=https://example.com/test/","http");

使用
strpost()
strpos()
稍微提高性能的版本:

检查第一个实例和最后一个实例是否不相同

$text = "http://plus.google.com/share?url=https://example.com/test/";
preg_match_all('/https?/', $text, $matches);
if (count($matches[0]) > 1) {
    // More than one match found.
}
 function countOccurences($haystack,$needle) {
    $count = 0;
    $offset = 0;
    while(($pos = strpos($haystack,$needle,$offset)) !== FALSE) {
        $count++;
        $offset = $pos + strlen($needle);
        if($offset >= strlen($haystack)) {
            break;
        }
    }
    return $count;
 }

echo countOccurences("https://plus.google.com/share?url=https://example.com/test/","http");
$appears_more_than_once = strpos($string, 'http') !== strrpos($string, 'http');