使用正则表达式查找字符串是否在数组内并替换它 + PHP


Using Regex to find if the string is inside the array and replace it + PHP

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

你知道怎么做吗?我不是正则表达式的主人,所以任何帮助都将不胜感激和奖励!

谢谢!

为什么是正则表达式?

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

也许这会有所帮助

foreach ($restricted_images as $key => $value) {
    if (strpos($string, $value) >= 0){
        $string = 'replace';
    }
}

你真的不需要正则表达式,因为你正在寻找直接的字符串匹配。

你可以试试这个:

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

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

$test = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
foreach($restricted_images as $restricted) {
    if (substr_count($test, $restricted)) {
        $test = 'FORBIDDEN';
    }
} 
// 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);