Question

I have a string that Im retrieving from xcode that contains some coordinates, when the string is inserted into the database it shows as:

(
    "37.351701,-122.105898",
    "37.351945,-122.106109",
    "37.352183,-122.106338"
)

I need the string to be:

37.351701,-122.105898,
37.351945,-122.106109,
37.352183,-122.106338

Im using str_replace, it removes the () but an empty line is left:

//empty line
37.351701,-122.105898,
37.351945,-122.106109,
37.352183,-122.106338
//empty line

The code Im using, how can I remove the empty lines?

<?php
$conn = mysql_connect($host, $user, $pass);
@mysql_select_db($db) or die("Unable to find database");
$trackArray = $_GET["trackArray"];

$trackArrayOutput = str_replace( array('"', '(' , ')', ' ', '\n', '\r', '\n\r'), '', $trackArray);

$query = "INSERT INTO routes VALUES ('', '$trackArrayOutput')";

mysql_query($query) or die (mysql_error("error"));
mysql_close();
?>
Was it helpful?

Solution 3

\n\r is not a valid line ending; you mean CRLF - \r\n. trim() is also very useful for removing beginning/trailing white-space and line breaks:

$trackArrayOutput = str_replace( array('"', '(' , ')'), '', $trackArray);
$trackArrayOutput = trim($trackArrayOutput);

OTHER TIPS

$myvar = " cool huh ?     ";

//trim it
$myvar = trim($myvar);

//now echo
echo $myvar ;  //result will be  

cool huh?

You've come across a PHP gotcha.

Change your replacement from:

array('"', '(' , ')', ' ', '\n', '\r', '\n\r')

to:

array('"', '(' , ')', ' ', "\n", "\r")

'\n' doesn't give you the newline character. You need the " to have PHP evaluate the string.

For clarification: var_dump('\n' === "\\n"); // true


Note that the output will be:

37.351701,-122.105898,37.351945,-122.106109,37.352183,-122.106338

so everything is on one line.

CRLF won't work when between single quotes.

To replace them, use : "\r\n" not '\r\n'.

Here is a dirty hack that can help too :

function noNl($string){
    return str_replace("<br />","",nl2br($string));
}
$trackArray = trim($_GET["trackArray"]);
$query = "INSERT INTO routes VALUES ('', '$trackArrayOutput')";

Split the problem into different steps:

// convert all newlines to '\n'
$str = str_replace( array("\n","\r","\r\n"), "\n", $str);

// remove first line
$str = substr($str, strpos($str, "\n")+1 );

// remove last line
$str = substr($str, 0,strrpos($str, "\n")-1);

// remove the spaces
$str = str_replace(' ', '', $str);

Online demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top