[英]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".
为单词"replace".
你知道怎么做那个吗? 我不是RegEx的主人,所以任何帮助都会受到高度赞赏和奖励!
谢谢!
也许这可以帮助
foreach ($restricted_images as $key => $value) {
if (strpos($string, $value) >= 0){
$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 $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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.