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;
}
Related
i have a string in the format ["gated","gas"] i want this to be in the format as : gated,gas.
for this i have used str_replace function and i also get the required output but i want some alternate to do this task.
$newArray['Ameneties'] = ["gated","gas"] this is a string not an array
$a = str_replace('"', '',$newArray['Ameneties']);
$b = str_replace('[', '',$a);
$c = str_replace(']', '', $b);
echo $c;
i got the right output but i think there should be correct way of doing this as i have used the str_replace multiple times
One quick way is to json_decode and implode
echo implode( ",", json_decode( '["gated","gas"]' ));
This will return to:
gated,gas
You can replace string more than 1,
$string = str_replace(array('[', '"', ']'), '', '["gated","gas"]');
echo $string; // Output: gated,gas
Docs : str_replace
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' ) );
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
How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?
You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);
Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.
Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.
Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>
I have a little problem with my function:
function swear_filter($string){
$search = array(
'bad-word',
);
$replace = array(
'****',
);
return preg_replace($search , $replace, $string);
}
It should transform "bad-word" to "**" but the problem is the case sensivity
eg. if the user type "baD-word" it doesn't work.
The values in your $search array are not regular expressions.
First, fix that:
$search = array(
'/bad-word/',
);
Then, you can apply the i flag for case-insensitivity:
$search = array(
'/bad-word/i',
);
You don't need the g flag to match globally (i.e. more than once each) because preg_replace will handle that for you.
However, you could probably do with using the word boundary metacharacter \b to avoid matching your "bad-word" string inside another word. This may have consequences on how you form your list of "bad words".
$search = array(
'/\bbad-word\b/i',
);
Live demo.
If you don't want to pollute $search with these implementation details, then you can do the same thing a bit more programmatically:
$search = array_map(
create_function('$str', 'return "/\b" . preg_quote($str, "/") . "\b/i";'),
$search
);
(I've not used the recent PHP lambda syntax because codepad doesn't support it; look it up if you are interested!)
Live demo.
Update Full code:
function swear_filter($string){
$search = array(
'bad-word',
);
$replace = array(
'****',
);
// regex-ise input
$search = array_map(
create_function('$str', 'return "/\b" . preg_quote($str, "/") . "\b/i";'),
$search
);
return preg_replace($search, $replace, $string);
}
I think you mean
'/bad-word/i',
Do you even need to use regex?
function swear_filter($string){
$search = array(
'bad-word',
);
if (in_array(strtolower($string), $search){
return '****';
}
return $search
}
makes the following assumptions.
1) $string contains characters acceptable in the current local
2) all contents of the $search array are lowercase
edit: 3) Entire string consists of bad word
I suppose this would only work if the string was split and evaluated on a per word basis.