how to add double quotation character in PHP string using str_replace - php

I have String in PHP like:
[x,y,z]
and I want to change it to
["x", "y", "z"]
I used str_replace but I can't represent the double quotation mark " in it like this
$modified = str_replace("[", "["", $NodeIDs);
I also used \ before it like java but it appears in the output. how can I do this?

You can use double quotes " inside single quotes ':
$modified = str_replace("[", '["', $NodeIDs);
Or escape them:
$modified = str_replace("[", "[\"", $NodeIDs);
Or this might be a better approach to get the desired result:
$letters = explode(',', trim($NodeIDs, '[]'));
$NodeIDs = '["' . implode('","', $letters) . '"]';

Another option is using trim, explode and json_encode:
$output = json_encode(explode(',', trim('[x,y,z]', "[]")));
print_r($output);
//["x","y","z"]
Ideone Demo

Single quotes should do the trick:
$modified = str_replace("[", '["', $NodeIDs);
Good luck to you on your project!

Simply do this
Use trim for removing the [, ] from the string, then use explode function to get the exploded string and then implode them.
$str = '[x,y,z]';
$arr = explode(",", trim($str, "[]"));
echo $str = '["'.implode('","', $arr).'"]'; //["x","y","z"]

Related

Changing normal quotes to curly ones in php

I'm trying to change straight quotes ("something") to curly quotes („something“) in PHP. Other answers are not for my situation, since I have a product details imported from DB as variable, using str_replace I've managed to only change it to „ and it seems like I can't change the second one to be “. From what I know, there is no way to accomplish this.
For example:
$description outputs -> Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.
What I would like:
$description outputs -> Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Try using preg_replace with the pattern "(.*?)". Then, replace with the capture group $1 inside curly quotes.
$input = "Hello \"everyone\", I would like to \"change\" this straight \"quotes\" to \"curly\" ones.";
$output = preg_replace("/\"(.*?)\"/", "„$1“", $input);
echo $output;
This prints:
Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Edit:
You are trying to replace HTML code, where double quotes have been encoded, so try the following:
$input = "Exklusiv von buttinette: Baumwollstoff "Leo",";
$output = preg_replace("/"(.*?)"/", "“$1”", $input);
echo $output;
This prints:
Exklusiv von buttinette: Baumwollstoff “Leo”,
Using explode and array_reduce:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$parts = explode('"', $str); // or explode('"', $str);
$carry = array_shift($parts);
$result = array_reduce($parts, function ($c,$i) {
static $up = false;
return $c . ((true === $up=!$up) ? '„' : '“') . $i;
}, $carry) ;
demo
Obviously if your original quotes are html entities you have to change the first parameter of explode.
Using strtok:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$result = substr(strtok(".$str", '"'), 1);
while (false !== $part = strtok('"')) {
$result .= "„${part}“" . strtok('"');
}
demo

how to omit double quotes and array brackets from a string in php

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

Add double quote between text seperated by comma [duplicate]

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)."\"";

PHP function that convert 'a,b' to ' "a","b" ' [duplicate]

This question already has answers here:
Add quotation marks to comma delimited string in PHP
(5 answers)
Closed 1 year ago.
I have a variable with string value of 'laptop,Bag' and I want it to look like ' "laptop","Bag" 'or "laptop","Bag". How could I do this one? Is there any php function that could get this job done? Any help please.
This would work. It first, explodes the string into an array. And then implodes it with speech marks & finishes up by adding the opening & closing speech mark.
$string = "laptop,bag";
$explode = explode(",", $string);
$implode = '"'.implode('","', $explode).'"';
echo $implode;
Output:
"laptop","bag"
That's what str_replace is for:
$result = '"'.str_replace(',', '","', $str).'"';
This would be very easy to do.
$string = 'laptop,bag';
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
That should turn 'laptop,bag' into "laptop","bag".
Wrapping that in a function would be as simple as this:
function changeString($string) {
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
return $newString;
}
I think you can explode your string as array and loop throw it creating your new string
function create_string($string)
{
$string_array = explode(",", $string);
$new_string = '';
foreach($string_array as $str)
{
$new_string .= '"'.$str.'",';
}
$new_string = substr($new_string,-1);
return $new_string;
}
Now you simply pass your string the function
$string = 'laptop,Bag';
echo create_string($string);
//output "laptop","Bag"
For your specific example, this code would do the trick:
<?php
$string = 'laptop,bag';
$new_string = ' "' . str_replace(',', '","', $string) . '" ';
// $new_string: "laptop","bag"
?>
That code would also work if you had more items in that list, as long as they are comma-separated.
Use preg_replace():
$input_lines="laptop,bag";
echo preg_replace("/(\w+)/", '"$1"', $input_lines);
Output:
'"laptop","Bag"'
I think you can perform that using explode in php converting that string in to an array.
$tags = "laptop,bag";
$tagsArray = explode(",", $tags);
echo $tagsArray[0]; // laptop
echo $tagsArray[1]; // bag
Reference
http://us2.php.net/manual/en/function.explode.php
related post take a look maybe could solve your problem.
How can I split a comma delimited string into an array in PHP?

php str_replace problem with single quote getting converted to &039

I am using str_replace to replace some characters and for some reason the output converts single quotes to &039. I am not trying to replace single quotes at all. What can be causing this?
$v = yourstring;
$newv = str_replace("&039", "'", $v);
Example:
$v = "Hi My Name Is &039George&039";
$newv = str_replace("&039", "'", $v);
echo $newv;
The Output Would Be:
Hi My Name Is 'George'
Now I just hope this helps a little and I hope I understood your question right.
Maybe some sort of conversion could be useful:
$v = $_GET['value'];
$v1 = html_entity_decode($v);
You can convert them back with something like
html_entity_decode(__("Some Text"), ENT_QUOTES, "UTF-8")

Categories