Alan Kis
Alan Kis

Reputation: 1910

How to search and remove various string in array elements?

I have array with login data, where I need to remove various, user defined strings, for example, my array looks like:

Array ( [0] => Date: 16/03/2015 20:39 [1] => IP Address: 93.136.99.89 [2]

What I want to do is remove "Date:" from first array element and "IP Address" from second array element.

Now I am using str_replace:

$lastlogindate = str_replace('Date:', 'Datum:', $lastlogin[0]);

But is there more elegant way of do this, and maybe, find defined occurance, and then wrapp it with tag, for every defined occurance in string in array element?

Upvotes: 0

Views: 90

Answers (2)

Dhiraj
Dhiraj

Reputation: 33618

You can also use regex to replace like this

preg_replace("/(.*?: )(.*)/", "$2", $input); by iterating over your array and replacing each value.

$input = array( 0 => 'Date: 16/03/2015 20:39', 1 => 'IP Address: 93.136.99.89' );

$array_output = array();
foreach ($input as $key => $value){
    array_push($array_output, preg_replace("/(.*?: )(.*)/", "$2", $value));
}
var_dump($array_output);

// this is the output
array(2) {
  [0]=>
  string(16) "16/03/2015 20:39"
  [1]=>
  string(12) "93.136.99.89"
}

Hope this helps

Upvotes: 0

marian0
marian0

Reputation: 3327

You can also still use str_replace(), but pass array arguments to it:

$lastlogindate = str_replace(array('Date: ', 'IP Address: '), '', $lastlogin);

For input array:

$lastlogin = ['Date: 16/03/2015 20:39', 'IP Address: 93.136.99.89'];

It returns you:

Array ( [0] => 16/03/2015 20:39 [1] => 93.136.99.89 )

Upvotes: 1

Related Questions