0

私は現在これを持っていますが、完璧ではありません:

$testcases = array(
array("I love mywebsite.com", true),
array("mywebsite.com/ is what I like", true),
array("www.mywebsite.com is my website", true),
array("Check out www.mywebsite.com/", true),
array("... http://mywebsite.com ...", true),
array("... http://mywebsite.com/ ...", true),
array("... http://www.mywebsite.com ...", true),
array("... http://www.mywebsite.com/ ...", true),
array("I like commas and periods. Just like www.mywebsite.com, they do it too!", true),
array("thisismywebsite.com is a lot better", false),
array("The URL fake.mywebsite.com is unknown to their server", false),
array("Check out http://redirect.mywebsite.com/www.ultraspammer.com", false)
);

function contains_link($text) {
return preg_match("/(https?:\/\/(?:www\.)?|(?:www\.))mywebsite\.com/", $text) > 0;
}

foreach ($testcases as $case) {
echo $case[0] . "=".(contains_link($case[0]) ? "true" : "false") . " and it should be " . ($case[1] ? "true" : "false") . "<br />";
}

出力:

I love mywebsite.com=false and it should be true
mywebsite.com/ is what I like=false and it should be true
www.mywebsite.com is my website=true and it should be true
Check out www.mywebsite.com/=true and it should be true
... http://mywebsite.com ...=true and it should be true
... http://mywebsite.com/ ...=true and it should be true
... http://www.mywebsite.com ...=true and it should be true
... http://www.mywebsite.com/ ...=true and it should be true
I like commas and periods. Just like www.mywebsite.com, they do it too!=true and it should be true
thisismywebsite.com is a lot better=false and it should be false
The URL fake.mywebsite.com is unknown to their server=false and it should be false
Check out http://redirect.mywebsite.com/www.ultraspammer.com=false and it should be false
4

3 に答える 3

13

正規表現の代替: parse_url()

$url = parse_url($text);
if($url['host'] == 'www.mywebsite.com' || $url['host'] == 'mywebsite.com')

アップデート:

$text多くのドメインを持つことができると仮定して、strstr()代わりに使用してください。

if(strstr($text,"mywebsite.com") !== FALSE)

更新 2:

function contains_link($text) {
        return preg_match("/(^(https?:\/\/(?:www\.)?|(?:www\.))?|\s(https?:\/\/(?:www\.)?|(?:www\.))?)mywebsite\.com/", $text);
}

と:

  contains_link("AAAAAAA http://mywebsite.com"); //1
  contains_link("foo BAaa http://www.mywebsite.com"); //1
  contains_link("abc.com www.mywebsite.com"); // 1
于 2012-05-08T16:23:36.170 に答える
5

私はあなたが探しているのはこれだと思います:

^(https?://)?(www\.)?mywebsite\.com/?

ここで実際に見てください: http: //regexr.com?30t6m


これがPHPです:

function contains_link($text) {
    return preg_match("~^(https?://)?(www\.)?mywebsite\.com/?~", $text);
}

PSその後に何もないことを確認したい場合は$、最後にaを追加する必要があります。

于 2012-05-08T16:21:32.240 に答える
4

テキストのみを検索する場合:

strpos($text, "mywebsite.com") !== FALSE

正確な「単語」を検索したい場合 (開始):

preg_match("/(^|\s)(https?:\/\/)?(www\.)?mywebsite\.com/", $text);

または (開始と終了):

preg_match("/(^|\s)(https?:\/\/)?(www\.)?mywebsite\.com\/?(\s|[,.]|$)/", $text);
于 2012-05-08T16:26:56.853 に答える