dongra1984 2019-02-21 20:20
浏览 107
已采纳

正则表达式如何匹配除变量内容之外的所有内容(PHP)

I'm returning some data as an array from a mySQL table using PHP, and need to replace some values with empty strings.

I'm wondering if it's possible for me to use a regular expression to match everything except the contents of a variable, the variable contains an email addresses (if that makes any odds) and the email address (can) appear in each array value.

As an example, I would want everything except "email@email.com" to be matched, so that I could replace all other instances in the array with an empty string, but not "email@email.com".

I've achieved the outcome I want using a string value, and a function that replaces 'valueA' with 'valueB' but not using a variable so far.

Example of the while loop that is returning the rows of data from the SQL query, and the static string variable that i've used to test the search and replace.

while($row = $result->fetch_assoc()) {
    $replace = "email@email.com";        
    print_r(str_replace($replace,"",$row,$i));
    echo "Replacements: $i";

I did wonder if this is possible with an SQL query (i.e filtering to column values that contain the variable that i'm interested in) - but I couldn't find a way to do that without writing lots of and statements.

This is my current SQL query:

$sql = ("SELECT * FROM calendar WHERE `8am` = '$currentUser' OR `9am` = '$currentUser' OR `10am` = '$currentUser'")

Thanks

  • 写回答

1条回答 默认 最新

  • dongnianchou7047 2019-02-21 20:36
    关注

    From comments it becomes clear you are looking for exact matches, and where a value deviates it should become an empty string.

    So then for a given $row:

    $replace = "email@email.com";
    foreach ($row as $i => $s) {
        if (strcasecmp($s, $replace)) $row[$i] = "";
    }
    

    Now the deviating email addresses have been replaced with an empty string. The comparison is case insensitive since in practice case is not significant in most email addresses. Otherwise do a strict comparison with ===.

    There is no good use here for a regular expression.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab