简体   繁体   中英

To replace the <br> with the <n> in php in an array

<?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>/",'\n',$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.

Change:

$dta=preg_replace("/<br>/",'\n',$dta);

To:

array_walk($dta, function(&$val){
    $val = str_replace("<br>", "\r\n", $val);
});

& keep in mind:

  • For \\n use double quotes " instead of single quotes ' .
  • If the resulted string having new lines will be used in Windows, replace with \\r\\n instead of just \\n
  • There is no need for preg_replace , str_replace would perfectly fit
  • As $dta is an array, we have to use array_walk or loop in the array.

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 />'],"\n",$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(){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM