<?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:
qwe <br> qu
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:
\\n
use double quotes "
instead of single quotes '
. \\r\\n
instead of just \\n
preg_replace
, str_replace
would perfectly fit $dta
is an array, we have to use array_walk
or loop in the array. Your code has so many bugs.
$fetch
holds an array (not a string) $dta
is then an array of arrays. 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.