来自MySQL的正则表达式

时间:2013-02-26 20:13:41

标签: php mysql regex

我在MySQL中有一个表,其中包含几个我想传递给preg_replace

的表达式

我的代码:

$q = mysql_query("SELECT * FROM TABLE");
while($r=mysql_query($q)) {
  $expressions = $r['expressions'];
}
$expressions = explode("\n", $expressions);
foreach ($expressions as $expression) {
  $content = preg_replace($expression, '', $content);
}

数据库中的一些数据:

#<div class="FBTbtn">(.*?)</div>#
#<!-- Extra Link -->(.*?)<!-- End Of Extra Link -->#
#<a(.*?)/a>#
#Learn More:#

2 个答案:

答案 0 :(得分:0)

如mysql_query()函数页面所述,使用mysql_fetch_assoc()遍历结果。 http://php.net/manual/en/function.mysql-query.php

$content = 'foo bar baz';
$result = mysql_query("SELECT * FROM expressions");
while ($row = mysql_fetch_assoc($result)) {
    $content = preg_replace($row['expression'], '', $content);
}

顺便说一下,不推荐使用mysql _ *()函数。你应该切换到PDO。 http://php.net/manual/en/book.pdo.php

答案 1 :(得分:0)

我用“,”而不是“\ n”

修复了它

代码:

$q = mysql_query("SELECT * FROM TABLE");
while($r=mysql_query($q)) {
  //Remove last "," from string
  $expressions = rtrim($r['expressions'], ",");
}
//Explode string into array based on "," instead of "\n"
$expressions = explode(",", $expressions);
foreach ($expressions as $expression) {
  $content = preg_replace($expression, '', $content);
}

数据库中的数据应如下所示:

#<div class="FBTbtn">(.*?)</div>#,#<!-- Extra Link -->(.*?)<!-- End Of Extra Link -->#,#<a(.*?)/a>#,#Learn More:#,