0

Im running strpos on a <a> tag to see if it contains either one of two urls.

At the moment im using this bellow - how would i set it to check if - tumblr.com OR google.com were present ?

function find_excluded_url ($url) {

    $find = "tumblr.com"; // OR GOOGLE.COM ....

    $pos = strpos($url, $find);

    if ($pos === false) {
        return false;
    } else {
        return true;
    }
}



// SET URL
   $url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";



// CALL FUNC
$run_url = find_excluded_url($url);

if ($run_url == true) {
    echo "URL - " . $url . "<br>";
}
sam
  • 9,486
  • 36
  • 109
  • 160

3 Answers3

5

You can't use two needles in strpos. But what you can do, is use it twice, with an or:

function find_excluded_url ($url) {
  return (strpos($url, "tumblr.com")!==false) || (strpos($url, "google.com")!==false);
}
Alex Siri
  • 2,856
  • 1
  • 19
  • 24
0

For more complicated searches, you might want to look into Regular Expressions. This would work:

$subject = 'blablabgoogle
  balblabtumblrasd
  blaasdgoogleadsad';

$pattern = '@(?:google\.com|tumblr\.com)@i';

$result = preg_match($pattern, $subject, $subpattern, PREG_OFFSET_CAPTURE);

if($result) echo 'Position: ' . $subpattern[0][1];

The performance of this (if performance is an issue for you) depends on how many search queries you have and how big your haystack is. Regular expressions come with a relatively big overhead, however, they only have to run over the text once. If you use strpos twice, this gets expensive with long strings. If performance is really an issue, you could also write your own strpos that goes character per character. I doubt, however, that this is necessary.

mrks
  • 8,033
  • 1
  • 33
  • 62
0
function find_excluded_url ($url, $searchURL) {
    $pos = strpos($url, $searchURL);
    if ($pos === false) {
        return false;
    } else {
        return true;
    }
}

// SET URL
   $url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";

// CALL FUNC
$run_url = find_excluded_url($url, 'google.com');
if ($run_url == true)
    echo "URL - " . $url . "<br>";

$run_url = find_excluded_url($url, 'tumblr.com');
if ($run_url == true)
    echo "URL - " . $url . "<br>";
suspectus
  • 16,548
  • 8
  • 49
  • 57