[英]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.