user2413244
user2413244

Reputation: 241

PHP: check if string contain the same word more than once

I have to check if string contains http or https more than once.

For example:

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

Or it can be:

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

The http and the https can be mixed

Upvotes: 1

Views: 4709

Answers (5)

Pere
Pere

Reputation: 1973

Slightly more performant version using strpos() and strrpos():

$appears_more_than_once = strpos($string, 'http') !== strrpos($string, 'http');

Checks if first instance and last are not the same.

Upvotes: 1

zrinath
zrinath

Reputation: 106

You could use a regex to search for both http and https:

$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.
}

Upvotes: 0

Dhananjay Badaya
Dhananjay Badaya

Reputation: 43

You can use strpos.
strpos returns the position of first occurrence of a substring in a string.
To find all the occurrences call strpos repeatedly, passing the return value of last strpos call + length of substring as the offset.

 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");

Upvotes: -2

Ray O'Donnell
Ray O'Donnell

Reputation: 781

You could use preg_match_all() which returns the number of matches found.

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

Upvotes: 0

0x5C91
0x5C91

Reputation: 3505

Well, since if your string contains "https", then it also contains "http", you can directly count the occurrences of "http", for example by using the function substr_count:

if(substr_count($your_string, "http") > 1) {
  // do something
}
else {
  // do something else
}

Upvotes: 13

Related Questions