Question: Hi I encounter some trouble when trying to save php variable to mysql database from shell\_exec result.

I want to get my local ip system in ubuntu, so I use 

```
<?php
    $ip = shell_exec("/sbin/ifconfig eth0 | grep 'inet addr:'| cut -d: -f2 | awk '{ print $1}' | tr -d ' '");
?>

```

I insert the $ip variable to mysql database, apparently there are some hidden character from the exec result

```
+------------+-----------------+-------------------+------------+------------+
| monitor_id | ip_address      | total_transaction | total_user | total_hits |
+------------+-----------------+-------------------+------------+------------+
|         70 | 
10.151.32.187
 |                 5 |          0 |          4 |
+------------+-----------------+-------------------+------------+------------+

```

looks like there are so many whitespaces, I already trim the whitespace with the following syntax :

```
str_replace(" ","",$ip);

```

and many other way but it returns the same. Can anybody help? Please..

Answer: 
`str_replace` only replaces the exact strings you pass it. It's not spaces that are causing the problem here; it's newlines. And you're not replacing those.

You could say something like

```
$ip = str_replace(["\n", "\r"], "", $ip);

```

to get rid of them before putting them in the database. But really, since an IP address shouldn't have spaces at all, you'd do better to say

```
$ip = trim($ip);

```

That'll remove *any* whitespace\* (including spaces, CRs, and newlines) from either end of the string (and if it came from the OS, that should be the only whitespace you have to worry about).

\* Any *ASCII* whitespace, anyway. If you want UTF-8 support, you might want to try `preg_replace('/\p{Z}+/us', '', $ip)`. But that's probably overkill here; the programs you're running won't output the more exotic types of whitespace.)
`trim()` will replace all whitespace characters at the beginning and end of the string.

If you want to replace all whitespace characters, regardless of where they are in the string, you can use preg\_replace like so:

```
$string = preg_replace('/\s+/', '', $string);

```