I am trying to process copied text from a website.
I am using iMacros to get the content from table and extracted data has lots of spaces between data.
I was trying trim and str_replace to remove spaces and it works but the problem I have is that when I am trying to explode new string, it looks like I am exploding original one, before trimming! Array has hundreds of keys!
What I am doing wrong?
Sample data:
"1","
Data1
","
Data2
","
Data3
","-","-1","-","-","-","-"
Here is a code that I'm using:
$data_lines = preg_split( '/\r\n|\r|\n/', $_POST['data'] );
foreach($data_lines as $data_line) {
$data_line = str_replace(' ', '', $data_line);
$data_line = str_replace('"', '', $data_line);
$data_line = explode(',', $data_line);
echo '<pre>';
print_r($data_line);
echo '</pre>';
}
So the goal is to get Data values and symbols/numbers in quotes (obviously whiteout the quotes) in array.
Thanks for help in advance
How about:
$data = explode(',', preg_replace(
array('/\r\n|\r|\n/', '/"\s*(\S*?)\s*"/'),
array('' , '$1' ),
$_POST['data']
));
working example
Use Trim function in php
trim — Strip whitespace (or other characters) from the beginning and end of a string - php.net
http://php.net/manual/en/function.trim.php
Related
I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs
I am trying to import urls from a list of URLS using the explode function.
For example, let's say
<?php
$urls = "http://storage.google.com/gn-0be5doc/da7f835a8c249109e7a1_solr.txt
http://google.com/gn-0be5doc/1660ed76f46bfc2467239e_solr.txt
http://google.com/gn-0be5doc/6dffbff7483625699010_solr.txt
http://google.com/gn-0be5doc/ef246266ee2e857372ae5c73_solr.txt
http://google.com/gn-0be5doc/d0565363ec338567c79b54e6_solr.txt
http://google.com/gn-0be5doc/43bd2d2abd741b2858f2b727_solr.txt
http://google.com/gn-0be5doc/eb289a45e485c38ad3a23bc4726dc_solr.txt";
$url_array = explode (" ", $urls);
?>
Considering that there is no delimeter here, the explode functions returns the whole text together.
Is there a way I can get them separately? Perhaps use end of url as the txt part?
Thanks in advance.
looks like all you need:
$urls = explode( "\n",$urls );
or
$urls = explode( "\r\n", $urls );
if you must you could use http://
If it was a string with out breaks then:
$urls = "http://storage.google.com/gn-0be5doc/da7f835a8c249109e7a1_solr.txthttp://google.com/gn-0be5doc/1660ed76f46bfc2467239e_solr.txthttp://google.com/gn-0be5doc/6dffbff7483625699010_solr.txthttp://google.com/gn-0be5doc/ef246266ee2e857372ae5c73_solr.txt";
$urls = preg_split('#(?=http://)#', $urls);
print_r($urls);
explode not used as it remove the delimiter
You clearly have line breaks in your code, and for line breaks with/without extra whitespace, you can use PHP_EOL as a delimiter:
$url_array = explode(PHP_EOL, $urls);
Sample Input String:
{"14" Alloy Wheels (Set of 4)":"N/A","Engine":"CrDi","15" Alloy Wheels":"optional","Other":"16" Wheels"};
There are 4 possible cases:
{"key"here":
,"Key"here":
:"Value"here",
:"Value"here"}
I need to get rid of the inverted commas in between keys and values, which is causing
invalid json
when using json_decode in PHP.
One possible solution is using RegEx, but I am not able to formulate the above possible cases.
I did some testing with your string and I came up with the following solution.
Set json formatting apart from the rest
Correct the keys and values
Restore json formatting
function repairJson( $str) {
$search = array( '":"', '","', '":{"', '"},"', '{"', '"}' );
$replace = array("':'", "','", "':{'", "'},'", "{'", "'}" );
// Distinct json default formatting
$str = str_replace( $search, $replace, $str );
// Find and replace all " that are not yet escaped
$str = preg_replace( '/([^\\\])"/', '${1}\"', $str );
// Restore json default formatting
$str = str_replace( $replace, $search, $str );
return $str;
}
This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";
I have this string that contains the following quote-contained, comma-separated values:
"field","anotherfield","yetanotherfield"
I need to populate an array with the content of these fields, without the quotes.
What I'm currently doing is:
$string = str_replace('"', NULL, $string);
and then
$array = explode(',', $string);
It works, but it breaks when there's a comma inside any field. How can I prevent this?
first, trim " from the start and end of string.
$string = trim('"field","anotherfield","yetanotherfield","other, another"', '"');
and after explode "," between values you need.
$array = explode('","', $string);
To parse entire CSV file into an array you could use str_getcsv function:
$array = array_map( 'str_getcsv', file( 'path-to-file/file.csv' ) );