dpnvrt3119 2017-04-20 10:36
浏览 86
已采纳

用数组中的php中的<n>替换<br>

<?php
  $servername="localhost";
  $username="root";
  $password="";
  $dbname="abc";
  $sql=mysqli_connect($servername,$username,$password,$dbname)
  $get=mysqli_query($sql,"SELECT * FORM table_name")

  $dta=array();
  while($fetch=mysqli_fetch_assoc($get)){
      array_push($dta,$fetch);
  }

  $dta=preg_replace("/<br>/",'
',$dta);
  $json=json_encode($dta);
  echo $json;
  exit;
?>

I want to replace the data form the data base. Want to replace column values from
with

For example:

  1. I have some columns like A, B, C
  2. Column A has data like qwe <br> qu
  3. I want the result of column A would be like qwe <n> qu

Note: The above small example has more than 20 columns.

  • 写回答

2条回答 默认 最新

  • duanning9110 2017-04-20 10:58
    关注

    Your code has so many bugs.

    1. $fetch holds an array (not a string)
    2. $dta is then an array of arrays.
    3. preg_replace works only on strings not arrays.

    You have first to fix that issue.

    Replace this line

    array_push($dta,$fetch);
    

    with this:

    //update all columns from the current fetched row
    $fetch = array_map(function($a){ 
           return str_replace(['<br/>','<br>','<br />'],"
    ",$a);
    },$fetch);
    //add the data
    array_push($dta,$fetch);
    

    and remove the preg_match line.

    What does ['<br/>','<br>','<br />'] in str_replace?

    If you have an array as first parameter then each entry will searched an replaced. In this example we dont really know how <br> is written in the code. Can be <br/> <br> <br />, so i have added all the cases here.

    More infos:

    http://php.net/manual/en/function.str-replace.php use of str_replace

    http://php.net/manual/en/function.array-map.php use of array_map

    http://php.net/manual/en/functions.anonymous.php use of function(){}

    https://stackoverflow.com/a/10304027/4916265 more about function()use(){}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line