Remove Last String if its ', ' - php

i have string like this
$string = 'aaaaaa, bbbbbb, cccccc, ';
and i want to modified it to be like this
$string = 'aaaaaa, bbbbbb, cccccc';
the last ',' and space is removed.
how to do this in php?
what is the function needed the achieve that?
my full code is like this
if(isset($_POST['accomodation'])) $accomodation = 'Accomodation, ';
if(isset($_POST['dance'])) $dance = 'Dance Lessons, ';
if(isset($_POST['vacation'])) $vacation = 'Vacation planning, ';
if(isset($_POST['group'])) $group = 'Group Vacation, ';
if(isset($_POST['inprivate'])) $inprivate = 'Private Vacation, ';
if(isset($_POST['land'])) $land = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
#$interest = $accomodation.$dance.$vacation.$group.$inprivate.$land;
#echo $string;
*sorry for such dumb question, it's been so long i didn't touch native PHP programming

rtrim() function:
rtrim($string,', ');
but how are you defining the string? It may be that you can build it without the comma and space.
EDIT
$interests = array();
if(isset($_POST['accomodation'])) $interests[] = 'Accomodation';
if(isset($_POST['dance'])) $interests[] = 'Dance Lessons';
if(isset($_POST['vacation'])) $interests[] = 'Vacation planning';
if(isset($_POST['group'])) $interests[] = 'Group Vacation';
if(isset($_POST['inprivate'])) $interests[] = 'Private Vacation';
if(isset($_POST['land'])) $interests[] = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
$interest = implode(', ',$interests);
echo $interest;

$string = preg_replace('/\s*,\s*$/', '', $string);
or, way cooler:
$string = rtrim($string, " ,");
Note that it does not matter the order of the characters in the pattern string.
#You last update.
This changes some things. You could put all your variables in one array and then implode it. Like so:
$items = array();
$items[] = $accomodation = 'Accomodation';
$items[] = $dance = 'Accomodation';
...
$result = implode(', ', $items)

$string = preg_replace( "/,\s*$/","",$string);
Should do the trick

Is it always a comma then a space at the end?
substr($string, 0, -2)

Often times, you can avoid the trailing comma altogether by changing the way you build the string. For example:
$count = 0;
foreach ($this as $that) {
if ($count != 0) {
$string .= ',';
}
$string .= $that['stuff'];
$count++;
}
Would remove the possibility of any trailing comma at the end, no matter the combination of results.

Related

First word of a comma separated sentence php

My string is : Hi my, name is abc
I would like to output "Hi Name".
[Basically first word of comma separated sentences].
However sometimes my sentence can also be Hi my, "name is, abc"
[If the sentence itself has a comma then the sentence is enclosed with ""].
My output in this case should also be "Hi Name".
So Far I've done this
$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter
foreach ($result as $results) {
$x = explode(' ',$results); // parsing with " " as delimiter
forach($x as $y){}
}
You can use explode to achieve YOUR RESULT and for IGINORE ' OR " use trim
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$first = explode(' ',$result[0]);
$first = $first[0];
$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
EDIT or if you want it for all , separated values use foreach
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$op = "";
foreach($result as $value)
{
$tmp = explode(' ',$value);
$op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);
Basically it's hard to resolve this issue using explode, str_pos, etc. In this case you should use state machine approach.
<?php
function getFirstWords($str)
{
$state = '';
$parts = [];
$buf = '';
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($char == '"') {
$state = $state == '' ? '"' : '';
continue;
}
if ($state == '' && $char == ',') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
$buf = '';
continue;
}
$buf .= $char;
}
if ($buf != '') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
}
return implode(' ', $parts);
}
foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
echo getFirstWords($str), PHP_EOL;
}
It will output Hi Name twice
Demo

How to explode string in pair, two key by slice in PHP

$myvar1 = 'this car is most new and fast';
$myvar2 = explode(' ', $myvar1); // slice on spaces
$myvar3 = implode( ',', $myvar2); //add comman
echo $myvar3;
output = this, car, is, most, new, and, fast
But I need this output = this car, is most, new and, fast
I need in pair output.
Thanks all.
This should do it:
<?php
$str = 'this car is most new and fast';
$str_explode = explode(' ', $str);
$str_result = '';
$comma = false;
foreach($str_explode AS $word) {
$str_result .= $word;
if($comma === false) {
$str_result .= ' ';
$comma = true;
} else {
$str_result .= ', ';
$comma = false;
}
}
echo $str_result;
It uses a boolean that is set to true and false every run so only every other word the comma is shown.
$myvar1 = 'this car is most new and fast';
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
$myvar1,$myvar2); // splits string on every other space
$myvar3 = implode( ',', $myvar2[0]); //add comman
echo $myvar3;
Instead of explode(), I have used preg_match_all() to split the string and implode() with ','
And here is your output:
this car,is most,new and,fast

replace all occurrences after nth occurrence php?

I have this string...
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"
How do I replace all the occurrences of | with " " after the 8th occurrence of | from the beginning of the string?
I need it look like this, 1|2|1400|34|A|309|Frank|william|This is the line here
$find = "|";
$replace = " ";
I tried
$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8);
but its not working out so well. If you have an idea please help!
You can use:
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('/^([^|]*\|){8}(*SKIP)(*F)|\|/', ' ', $text);
//=> 1|2|1400|34|A|309|Frank|william|This is the line here
RegEx Demo
Approach is to match and ignore first 8 occurrences of | using ^([^|]*\|){8}(*SKIP)(*F) and the replace each | by space.
You can use explode()
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text);
$result = '';
foreach($arr as $k=>$v){
if($k == 0) $result .= $v;
else $result .= ($k > 7) ? ' '.$v : '|'.$v;
}
echo $result;
You could use the below regex also and replace the matched | with a single space.
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*\|){8}|(?<!^)\G)[^|\n]*\K\|~', ' ', $text);
DEMO
<?php
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$texts = explode( "|", $text );
$new_text = '';
$total_words = count( $texts );
for ( $i = 0; $i < $total_words; $i++)
{
$new_text .= $texts[$i];
if ( $i <= 7 )
$new_text .= "|";
else
$new_text .= " ";
}
echo $new_text;
?>
The way to do that is:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text, 9);
$arr[8] = strtr($arr[8], array('|'=>' '));
$result = implode('|', $arr);
echo $result;
Example without regex:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$array = str_replace( '|', ' ', explode( '|', $text, 9 ) );
$text = implode( '|', $array );
str_replace:
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
explode:
If limit is set and positive, the returned array will contain a
maximum of limit elements with the last element containing the rest of
string.

PHP - Convert a string with dashes while removing first word

$title = '228-example-of-the-title'
I need to convert the string to:
Example Of The Title
How would I do that?
A one-liner,
$title = '228-example-of-the-title';
ucwords(implode(' ', array_slice(explode('-', $title), 1)));
This splits the string on dashes (explode(token, input)),
minus the first element (array_slice(array, offset))
joins the resulting set back up with spaces (implode(glue, array)),
and finally capitalises each word (thanks salathe).
$title = '228-example-of-the-title'
$start_pos = strpos($title, '-');
$friendly_title = str_replace('-', ' ', substr($title, $start_pos + 1));
You can do this using the following code
$title = '228-example-of-the-title';
$parts = explode('-',$title);
array_shift($parts);
$title = implode(' ',$parts);
functions used: explode implode and array_shift
$pieces = explode("-", $title);
$result = "";
for ($i = 1; $i < count(pieces); $i++) {
$result = $result . ucFirst($pieces[$i]);
}
$toArray = explode("-",$title);
$cleanArray = array_shift($toArray);
$finalString = implode(' ' , $cleanArray);
// echo ucwords($finalStirng);
Use explode() to split the "-" and put the string in an array
$title_array = explode("-",$title);
$new_string = "";
for($i=1; $i<count($title_array); $i++)
{
$new_string .= $title_array[$i]." ";
}
echo $new_string;

How do I combine all elements in an array using comma?

I know this question has with out any doubt been asked a whole lot of times. I though can seem to find a solution. So forgive me if it's way to simple.
The question is how do access the end of a while loop.
E.g.
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
echo $c . "," ;
}
How do I manage separate each value of the while loop by a comma but of course I don't want the comma at the end of the value.
In advance thank you very much for your help :)
You can:
1) Build a string, and remove the last character:
$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c .= $countByMonth["COUNT(id)"] . ',';
}
$c = substr($c, 0, -1);
echo $c;
2) Build an array and use implode()
$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c[] = $countByMonth["COUNT(id)"];
}
echo implode(',', $c);
Tip: You can use aliases in your query, like: SELECT COUNT(id) as count FROM .... Then you can access it as $countByMonth['count'], which looks cleaner IMO.
The simple1 solution:
$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
if ($isFirst) {
$isFirst = false;
} else {
echo = ', ';
}
echo $c;
}
Alternatively, you could implode() the values. Or - perhaps easier to read/understand/maintain - concatenate it all into a string and remove the last "," (SO eats my whitespace; the string is comma-whitespace):
$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
$list .= $c . ', ';
}
echo substring($list, 0, -2); // Remove last ', '
(Several other answers propose the use of an accumulated array and then use implode(). From a performance perspective this method will be superior to string concatenation.)
1 See comments.
Alternatively you can do:
$arr = array();
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$arr[] = $countByMonth["COUNT(id)"];
}
echo implode(', ',$arr);
Or afterwards just trim it off with rtrim($c, ',')
While I think the implode solution is probably best, in situations where you can't use implode, think of the basic algorithm differently. Rather than "how can I add a comma behind every element but the last?" ask yourself "how can I add a comma before every element but the first?"
$str = '';
$count = count( $array );
if( $count ) {
$i = 0;
$str = $array[$i];
$i++;
while( i < $count ) {
$str .= ','.$array[$i];
$i++;
}
}
If you "shift" the first element, then you can use a foreach loop:
$str = '';
if( count( $array ) ) {
$str = array_shift( $array );
foreach( $array as $element ) {
$str .= ', '.$element;
}
}
Ty this:
int count;//
while(i)
{
count=i;
}

Categories