2011-06-01 28 views
1

如何判断图片url,如果链接包含单词adsad,则将insert传入数据库。然后它应该插入到第一个数据,并通过第二个。谢谢,基于字符串内容的条件sql

PHP代码

foreach($data['image'] as $item) { 
    $title = $item['title']; 
    $image = $item['image_url']; 
    mysql_query("SET NAMES utf8"); 
mysql_query("INSERT INTO article (title, image) VALUES ('".$title."', '".$image."')"); 
} 

JSON树

{ 
    "image": [ 
     { 
      "title": "the big lake", 
      "image_url": "http://localhost/json/image/the_big_lake.jpg" 
     }, 
     { 
      "title": "Nike Air", 
      "image_url": "http://localhost/json/image/12087689_ads.jpg" 
     } 
    ] 
} 
+0

你的问题措辞不当。我知道你想检测'image_url'键中的字符串“ad”,但是我没有跟踪你想在这样的条件满足时做什么。 – 2011-06-01 17:53:24

+0

@Chris,我是否可以用'if(preg_match)'来首先做一名裁判? – cj333 2011-06-01 17:59:37

+0

我得到你想要一个**条件**(不是“判断”),但我不确定你想要做什么,如果条件为真。所以 - 如果文件名中有字符串“ad”...做什么?插入它?不要插入它? – 2011-06-01 18:01:53

回答

1

我假设你要插入不具有“广告”中的图像网址...如果您只想广告,if语句改变===!==所有图像。确保将其保留为三重平等或感叹号 - 双重平等。

还要注意,这不是一个非常可靠的方法 - 如果图像被称为“my_dad_and_mom.jpg”,该怎么办?它包含“广告”,但不是广告。

foreach($data['image'] as $item) { 
    if (strpos($item['image_url'], 'ad') === false) { 
    mysql_query("SET NAMES utf8"); // not sure why this is needed.... 
    mysql_query("INSERT INTO article (title, image) VALUES ('".$item['title']."', '".$item['image_url']."')"); 
    } 
} 

编辑:这是那种快速和肮脏......

$forbidden_words = array(
     'ads', 
     'ad', 
     'sex', 
     'xxx' 
    ); 
    function str_in_array($str, $array) { 
     foreach ($array as $token) { 
      if (stristr($str, $token) !== FALSE) 
       return true; 
     } 
     return false; 
    } 
foreach($data['image'] as $item) { 
    if (str_in_array($item['image_url'], $forbidden_words) === false) { 
    mysql_query("SET NAMES utf8"); // not sure why this is needed.... 
    mysql_query("INSERT INTO article (title, image) VALUES ('".$item['title']."', '".$item['image_url']."')"); 
    } 
} 
+0

谢谢,我可以使用数组在里面?如果'广告','广告'... ...你知道,许多讨厌的话... – cj333 2011-06-01 18:06:43

+0

增加了一个禁止的词语数组,并检查 – 2011-06-01 18:12:05

+0

是的功能,使一个功能可以解决它。谢啦:} – cj333 2011-06-01 18:17:01

1

这样吗?

foreach($data['image'] as $item) { 
    $title = $item['title']; 
    $image = $item['image_url']; 
    if(preg_match('/ad/',$image){ 
    mysql_query("SET NAMES utf8"); 
    mysql_query("INSERT INTO article (title, image) VALUES ('".$title."', '".$image."')"); 
    } 
} 
+0

它应该是'if(!preg_match('/ ad /',$ image)){' – cj333 2011-06-01 18:28:21

+0

“判断一个图片网址,如果该链接包含单词广告ad,然后将插入数据库”听起来像他想要的其他方式,这使得更有意义,虽然;) – Trey 2011-06-01 18:39:35

+0

我知道preg_match只允许一个单词匹配。但克里斯通过函数解决它。 – cj333 2011-06-01 19:24:13