I am getting a string output from MYSQL DB in the following format. Quotes are included.
"Created" to "Quote Sent"
How will i save this String as 2 variables using PHP.
For Example: $var1 = 'Created'
$var2 = 'Quote Sent'
I tried with explode, but not getting the desired output.
$string = '"Created" to "Quote Sent"';
$stringParts = explode("to", $string);
$var1 = $stringParts[0];
$var2 = $stringParts[1];
Can please anyone help me on this.?
You could do somthing like this:
<?php
$str = '"Created" to "Quote Sent"';
$var1 = str_replace('"', "", explode(" to ", $str)[0]);
$var2 = str_replace('"', "", explode(" to ", $str)[1]);
?>
Also you told us you tried this, what out put DID you get?
You should only be calling explode() once. And the more appropriate call to trim the double quotes from the string is: trim() with a character mask of ".
Code: (Demo)
$str = '"Created" to "Quote Sent"';
$parts = explode(' to ', $str, 2);
$var1 = trim($parts[0], '"');
$var2 = trim($parts[1], '"');
echo $var1;
echo "\n---\n";
echo $var2;
Output:
Created
---
Quote Sent
If you are crazy for a one-liner, you can use regex.
[$var1, $var2] = preg_match('~"([^"]+)" to "([^"]+)"~', $str, $out) ? array_slice($out, 1) : ['', ''];
or
[$var1, $var2] = preg_split('~"( to ")?~', $str, 3, PREG_SPLIT_NO_EMPTY); // need to allow 3rd empty element to be found & disregarded
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 the following string:
"{\"ttl\": null\054 \"card_id\": \"np\"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"
I can tidy this using strip slashes so it becomes:
"{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"
I need to get the value where np is however I am unsure how to do this. Is it best to remove the trailing text and address it as JSON or am I best using another method?
the string in question does contain the wrapping " "
Current Code:
echo stripslashes($VCIDcookie);
$string = stripslashes($VCIDcookie);
output of $string: "{"ttl": null54 "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg"
$string = explode('}', $string);
$json = json_decode($string[0] .'}');
echo $json->card_id;
Updated Code - I have used trim() to remove the wrapping quotation marks so the string doesn't have them but I am still not getting the np output:
$string = trim($VCIDcookie,'"');
$string = stripslashes($string);
echo $string;
$string = explode('}', $string);
$json = json_decode($string[0] .'}');
echo $json->card_id;
Try this :
$string = '{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('.', $string);
$json = json_decode($string[0]);
echo $json->card_id;
Care : I suppose ttl or card_id don't have "." in their values.
Or, to avoid problems with "." :
$string = '{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('}', $string);
$json = json_decode($string[0] .'}');
echo $json->card_id;
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:
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?
I have a string variable $nutritionalInfo, this can have values like 100gm, 10mg, 400cal, 2.6Kcal, 10percent etc... I want to parse this string and separate the value and unit part into two variables $value and $unit. Is there any php function available for this? Or how can I do this in php?
Use preg_match_all, like this
$str = "100gm";
preg_match_all('/^(\d+)(\w+)$/', $str, $matches);
var_dump($matches);
$int = $matches[1][0];
$letters = $matches[2][0];
For float value try this
$str = "100.2gm";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);
var_dump($matches);
$int = $matches[1][0];
$letters = $matches[2][0];
Use regexp.
$str = "12Kg";
preg_match_all('/^(\d+|\d*\.\d+)(\w+)$/', $str, $matches);
echo "Value is - ".$value = $matches[1][0];
echo "\nUnit is - ".$month = $matches[2][0];
Demo
I had a similar problem but none of the answers here worked for me. The problem with the other answers is they all assume you'll always have a unit. But sometimes I would have plain numbers like "100" instead of "100kg" and the other solutions would cause the value to be "10" and the units to be "0".
Here's a better solution I somewhat took from this answer. This will separate the number from ANY non-number characters.
$str = '70%';
$values = preg_split('/(?<=[0-9])(?=[^0-9]+)/i', $str);
echo 'Value: ' . $values[0]; // Value: 70
echo '<br/>';
echo 'Units: ' . $values[1]; // Units: %