Remove last character from a string [duplicate] - php

This question already has answers here:
How do I remove all specific characters at the end of a string in PHP?
(10 answers)
Closed 12 months ago.
I have a list of country as an array .. i want this array in following format to later return it via ajax :-
"india","usa","uk" ..
Used following code to get somewhat i was looking for ..
foreach($country_list as $country) {
$countries .= '"'.$country['label'].'",';
}
problem is it is giving output like "india","usa","uk", ... i.e with trailing comma .
Tried to remove it with
substr_replace($countries, "0", -1);
and
rtrim($countries, ",");
But didnt work ! .. Please help !

I think that you're missing to assign the variable back after the trim:
$s = '"india","usa","uk",';
$s = rtrim($s, ',');
// prints "india","usa","uk"
print $s;
Demo
Try before buy

try this substr() or mb_substr()
substr($string, 0, -1);
mb_substr($string, 0, -1);
or check this link

Have you tried using: str_replace(",", " ", $countries);
This function should replace each occurence of a comma with a space.

if (strlen($b) > 1){
$b = substr($b,0, -1);
}

Try this
$countries = [];
foreach($country_list as $country) {
$countries[] = $country['label'];
}
$new_array = implode(",", $countries);

Use implode instead:
$arr = array();
foreach($country_list as $country)
array_push($arr, $country['label']);
$comma_separated = implode(",", $arr);

Try this
create a variable ($comsep) and initialise it to an empty string.
in the foreach loop concatenate the variable ($comsep) at the start of the string.
add an extra statement in the foreach loop to set the variable ($comsep) to the value "," - after the concatenation statement.
This will put a comma at the start of each appended string except for the first one. The is no longer a trailing comma to deal with so no need to try trimming it off.

// Try to use chop() function in php. It helps in removing last character from a string
<?php
echo '<br>' .$country_name = "'USA','UK','India',";
echo '<br>' .chop($country_name,",");
exit;
?>
Output : 'USA','UK','India'

foreach($country_list as $country) {
$countries[] = $country['label'];
}
json_encode($countries);

Related

Get the last string of URL's

I am getting data from a page like this:
<?php $speaker = $page->uri();
$speakerEvents = page('program')->grandchildren()->filter(function($child) use($speaker) {
$speakers = $child->speaker()->toStructure();
return $speakers->findBy('selectspeaker', $speaker);
});
echo $speakerEvents;
?>
It's output is:
"page/page/pageIWant
page/page/pageIWant"
The Result I want is
pageIWant
pageIWant
I tried to get the last name with
echo basename($speakerEvents);
But I only get one of the last pageIWant
How do I get the last pages without removing the first URL?
Use the explode method to get array of URL
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
If your output is
page/page/pageIWant
page/page/pageIWant
<?php
$text = "page/page/pageIWant";
$text_arr = explode('/',$text);
echo $page = end($text_arr);
// this will print: pageIWant
?>
Your string has a line break as path separator. You need to split lines by either \r\n (CR-LF), \n, or \r which can be done with preg_split. If you can ensure one of the formats, you can also use the simple explode function.
foreach (preg_split('~(?:\r?\n|\r)~u', $speakerEvents) as $path)
echo basename($path) , PHP_EOL;
As AbraCadaver noted, you can add the flag PREG_SPLIT_NO_EMPTY to preg_split if you do not want empty lines to be handled.
If the double qoutes you show in the question are part of the string, you need further more to trim the string:
foreach (preg_split('~(?:\r?\n|\r)~u', trim($speakerEvents, '"')) as $path)
echo basename($path) , PHP_EOL;
You can explode the string e.g.
$array = explode('/', 'page/page/pageIWant');
Then you can retrieve it using the index like so:
$array[(count($array) - 1)];

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?

separate with commas

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How do I place a comma between each character in a string with PHP? [duplicate]

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

Categories