Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to add slashes into array

i have a problem i want to add slashes at the starting and the end of each string of my array.

This is an example of my actual array :

$patte = array();
$patte[0] = "httpd";
$patte[1] = "vsftpd";
$patte[2] = 'gohphp';
$patte[3] = 'abcdef';

i use this array for taking information into a DataBase so i can't place slashes now, or this is going to not working.

(mysql_query ... while mysql_fetch_array ...)

I need to rename these entry. For this i use a second array, and with the command : "preg_replace" i can translate every strings like i want. But preg_replace want me to add slashes in $patte

I want to obtain an array like this

$pattes = array();
$pattes[0] = "/httpd/";
$pattes[1] = "/vsftpd/";
$pattes[2] = '/gohphp/';
$pattes[3] = '/abcdef/';

Can you help me please. I'm gonna have like 1000 line into this array.

like image 355
user3114471 Avatar asked Jul 31 '26 17:07

user3114471


2 Answers

Using array_map() you can apply callback to every element of your array :

function addSlashes($str)
{
    return "/".$str."/";
}
$newArray = array_map("addSlashes", $patte);//array with the new values
like image 164
Charaf JRA Avatar answered Aug 02 '26 05:08

Charaf JRA


Use array_map:

$pattes = array_map(function($str) {
  return '/'.$str.'/';
}, $pattes);
like image 38
Florent Avatar answered Aug 02 '26 07:08

Florent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!