0
$restricted_images = array(
    "http://api.tweetmeme.com/imagebutton.gif",
    "http://stats.wordpress.com",
    "http://entrepreneur.com.feedsportal.com/",
    "http://feedads.g.doubleclick.net"
);

这是我想知道某个字符串是否具有那种字符串的图像列表。

例如:

$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/".

由于"http://api.tweetmeme.com/imagebutton.gif"是在$restricted_images数组中,也是变量内的字符串$string,所以它会将变量替换$string成一个单词"replace".

你知道怎么做吗?我不是 RegEx 的大师,所以任何帮助将不胜感激和奖励!

谢谢!

4

5 回答 5

1

也许这可以帮助

foreach ($restricted_images as $key => $value) {
    if (strpos($string, $value) >= 0){
        $string = 'replace';
    }
}
于 2012-07-11T08:56:25.023 回答
1

为什么是正则表达式?

$restricted_images = array(
    "http://api.tweetmeme.com/imagebutton.gif",
    "http://stats.wordpress.com",
    "http://entrepreneur.com.feedsportal.com/",
    "http://feedads.g.doubleclick.net"
);

$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
$restrict = false;
foreach($restricted_images as $restricted_image){
    if(strpos($string,$restricted_image)>-1){
        $restrict = true;
        break;
    }
}

if($restrict) $string = "replace";
于 2012-07-11T08:58:10.603 回答
0

您实际上并不需要正则表达式,因为您正在寻找直接的字符串匹配。

你可以试试这个:

foreach ($restricted_images as $url) // Iterate through each restricted URL.
{
    if (strpos($string, $url) !== false) // See if the restricted URL substring exists in the string you're trying to check.
    {
        $string = 'replace'; // Reset the value of variable $string.
    }
}
于 2012-07-11T08:57:02.397 回答
0

您不必为此使用正则表达式。

$test = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
foreach($restricted_images as $restricted) {
    if (substr_count($test, $restricted)) {
        $test = 'FORBIDDEN';
    }
} 
于 2012-07-11T08:59:41.460 回答
0
// Prepare the $restricted_images array for use by preg_replace()
$func = function($value)
{
    return '/'.preg_quote($value).'/';
}
$restricted_images = array_map($func, $restricted_images);

$string = preg_replace($restricted_images, 'replace', $string);

编辑:

如果您决定不需要使用正则表达式(您的示例并不真正需要),那么这是一个比所有这些foreach()答案更好的示例:

$string = str_replace($restricted_images, 'replace', $string);
于 2012-07-11T09:00:17.593 回答