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?
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
How can I convert to uppercase for the following example :
title-title-title
Result should be:
Title-Title-Title
I tried with ucwords but it converts like this: Title-title-title
I currently have this:
echo $title = ($this->session->userdata('head_title') != '' ? $this->session->userdata('head_title'):'Our Home Page');
In this particular string example, you could explode the strings first, use that function ucfirst() and apply to all exploded strings, then put them back together again:
$string = 'title-title-title';
$strings = implode('-', array_map('ucfirst', explode('-', $string)));
echo $strings;
Should be fairly straightforward on applying this:
$title = '';
if($this->session->userdata('head_title') != '') {
$raw_title = $this->session->userdata('head_title'); // title-title-title
$title = implode('-', array_map('ucfirst', explode('-', $raw_title)));
} else {
$title = 'Our Home Page';
}
echo $title;
echo str_replace(" ","-",ucwords(str_replace("-"," ","title-title-title")));
Fiddle
Output:
Title-Title-Title
Demo
Not as swift as Ghost's but a touch more readable for beginners to see what's happening.
//break words on delimiter
$arr = explode("-", $string);
//capitalize first word only
$ord = array_map('ucfirst', $arr);
//rebuild the string
echo implode("-", $ord);
The array_map() applies callback to the elements of the given array. Internally, it traverses through the elements in our word-filled array $arr and applies the function ucfirst() to each of them. Saves you couple of lines.
Edit #2
This isn't working for the new information added to op, as there is an answer this won't be updated to reflect that.
Edit #1
$var = "title-title-title";
$var = str_replace (" ", "_", ucwords (str_replace (" ", "_", $var));
Old, non-working
$var = "title-title-title";
$var = implode("-", ucwords (explode("-", $var)));
try the following:
$str='title-title-title';
$s='';
foreach(explode('-',$str) as $si){
$s.= ($s ? "-":"").ucfirst($si);
}
$s should be Title-Title-Title at this point
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'm using a PHP script to link each word of the string:
<?
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
?>
How do I link each word of the string $str without linking the <br>s?
You can just use preg_replace
// More complext string
$str = "hello<br> guys good man Google <br /> hurry";
// Url Template
$template = '%1$s';
// Replace Words
echo preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z]+)\b/is", sprintf($template, "\\1"), $str);
Output
hello
<br>
guys
good
man
Google
<br />
hurry
Use the strip_tags() function before/in your explode:
$arr = explode (' ', strip_tags($str));
Untested, but start with JvO's code and put the links back into the original string:
$str = "hello<br> guys good man";
$arr = explode (' ', strip_tags($str));
foreach($arr as $value) {
$link = ''.$value.'';
$str = str_replace($value, $link, $str);
}
echo $str;
Note that you can save time by removing duplicates from $arr.
Edit: in fact, you must remove duplicates from $arr, or things will get ugly:
$arr = array_unique(explode (' ', strip_tags($str)));
... and another edit to the original code for an error.
Before you form the link, process the string first:
$proc_val = preg_replace('/<br>/', '', $value);
echo ''.$value.'';
Not sure what you were saying in the comment of Jvo's answer, but you can always use the striptags in the foreach as well and only strip the link part.
foreach($arr as $value){
echo ''.$value.'';
}
So here is the full code:
<?
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
?>
You really should think about what explode(' ', $str) is going to do though.
Any time any HTML tag has attributes to it like <span style="color: red;"> you are going to run into trouble. You should strip_tags first, on the entire string, then process it. Keep an HTML version as a separate string if you need to add stuff later.
Why not just explode the string as you currently are and simply strip the tags in the URL.
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
This will output the following HTML which is what I believe you want.
hello<br>
guys
good
man
If the string is quite long, and can contain any number of tags, including <p>, <h1> and <br> as well as the more correct <br/>, you could consider parsing the lot, and use str_replace:
$string = 'Foo<br/>Hello Bar!';
$DOM = new DOMDocument;
//make sure all breaks are preceded by a space, if not words might be concatenated by accident
$DOM->loadHTML(str_replace('<br', ' <br', $string));
//get all nodes
$nodes = $DOM->getElementsByTagName('*');
//get the text, split it and replace, but keep track of replaced words
$replaced = array();
for ($i = 0, $j = $nodes->length; $i<$j;$i++)
{
$words = explode(' ',$nodes->item($i)->nodeValue);
while($word = array_shift($words))
{
if (!array_key_exists($word, $replaced))
{//avoid replacing twice (and thus creating a link within a link)
$replaced[$word] = true;
$string = str_replace($word, ''.$word.'', $string);
}
}
}
This code is tested and working.
*strong text*i have a string like that "x", "x,y" , "x,y,h"
i want to user preg replace to remove the commas inside the double qutations and return the string as
"x", "xy" , "xyh"
You can just use a regular replace.
$mystring = str_replace(",", "", $mystring);
You dont need preg_replace() here and whereever possible you should trying to avoid it
$string = str_replace(',', '', $string);
This would work fine: http://codepad.org/lq7I5wkd
<?php
$myStr = '"x", "x,y" , "x,y,h"';
$chunks = preg_split("/\"[\s]*[,][\s]*\"/", $myStr);
for($i=0;$i<count($chunks);$i++)
$chunks[$i] = str_replace(",","",$chunks[$i]);
echo implode('","',$chunks);
?>
I use the following, which I've found is generally faster than regexp for this type of replacement
$string = '"x", "x,y" , "x,y,h"';
$temp = explode('"',$string);
$i = true;
foreach($temp as &$value) {
// Only replace in alternating array entries, because these are the entries inside the quotes
if ($i = !$i) {
$value = str_replace(',', '', $value);
}
}
unset($value);
// Then rebuild the original string
$string = implode('"',$temp);