[英]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"
);
This are the list of images that I want to know if a certain string has that kind of string. 这是我想知道某个字符串是否有这种字符串的图像列表。
For example: 例如:
$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/".
Since "http://api.tweetmeme.com/imagebutton.gif"
is in the $restricted_images
array and it is also a string inside the variable $string
, it will replace the $string
variable into just a word "replace".
由于
"http://api.tweetmeme.com/imagebutton.gif"
位于$restricted_images
数组中,并且它也是变量$string
,因此它将$string
变量"replace".
为单词"replace".
Do you have any idea how to do that one? 你知道怎么做那个吗? I'm not a master of RegEx, so any help would be greatly appreciated and rewarded!
我不是RegEx的主人,所以任何帮助都会受到高度赞赏和奖励!
Thanks! 谢谢!
maybe this can help 也许这可以帮助
foreach ($restricted_images as $key => $value) {
if (strpos($string, $value) >= 0){
$string = 'replace';
}
}
why regex? 为什么正规用途?
$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";
You don't really need regex because you're looking for direct string matches. 你真的不需要正则表达式,因为你正在寻找直接字符串匹配。
You can try this: 你可以试试这个:
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.
}
}
You don't have to use regex'es for this. 你不必为此使用正则表达式。
$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);
Edit: 编辑:
If you decide that you don't need to use regular expressions (which is not really needed with your example), here's a better example then all of those foreach()
answers: 如果你决定不需要使用正则表达式(你的例子并不真正需要),这里有一个更好的例子,那么所有这些
foreach()
答案:
$string = str_replace($restricted_images, 'replace', $string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.