Replace the last comma with an & sign - php

I have searched everywhere but can't find a solution that works for me.
I have the following:
$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);
For this example lets say:
$studio = '1';
$one_bed = '3';
$two_bed = '3';
I then use the implode function to put a comma in between all the values:
$bedroom_list = implode(", ", array_filter($bedroom_array));
echo $bedroom_list;
This then outputs:
1, 2, 3
What I want to do is find the last comma in the string and replace it with an &, so it would read:
1, 2 & 3
The string will not always be this long, it can be shorter or longer, e.g. 1, 2, 3, 4 and so on. I have looked into using substr but am not sure if this will work for what I need?

Pop off the last element, implode the rest together then stick the last one back on.
$bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
$last = array_pop($bedroom_array);
$string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;
Convert & to the entity & if necessary.

if you have comma separated list of words you may use:
$keyword = "hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf, sdgdfg";
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $keyword);
echo $keyword;
it will output:
hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf & sdgdfg

A one-liner alternative, that will work for any size array ($b = $bedroom_array):
echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b);

strrpos finds the last occurrance of a specified string.
$str = '1, 2, 3';
$index = strrpos( $str, ',' );
if( $index !== FALSE )
$str[ $index ] = '&';

function fancy_implode($arr){
array_push($arr, implode(' and ', array_splice($arr, -2)));
return implode(', ', $arr);
}
I find this easier to read/understand and use
Does not modify the original array
Does not use regular expressions as those may fail if strings in the array contain commas, there could be a valid reason for that, something like this: array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
Delimiters don't have to be of the same length as with some of the other solutions

$bedroom_list = implode(", ", array_filter($bedroom_array));
$vars = $bedroom_list;
$last = strrchr($vars,",");
$last_ = str_replace(",","&",$last);
echo str_replace("$last","$last_",$vars);

<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>

Here's another way to do the replacement with a regular expression using a positive lookahead which doesn't require a backreference:
$bedroom_list = preg_replace('/,(?=[^,]*$)/',' &', implode(', ', $bedroom_array));

Related

How to check if comma separated strings have duplicate values in php

I have a variable that contains comma separated strings and I would like to create a check if this variable has duplicate strings inside without converting it into an array. If it would make it any easier, each comma separated strings have 3 characters.
example.
$str = 'PTR, PTR, SDP, LTP';
logic: if any of the strings has a duplicate value then display an error.
This should work for you:
Just use strtok() to loop through each token of your string, with , as delimiter. Then use preg_match_all() to check if the token is more than once in the string.
<?php
$str = "PTR, PTR, SDP, LTP";
$tok = strtok($str, ", ");
$subStrStart = 0;
while ($tok !== false) {
preg_match_all("/\b" . preg_quote($tok, "/") . "\b/", substr($str, $subStrStart), $m);
if(count($m[0]) >= 2)
echo $tok . " found more than 1 times, exaclty: " . count($m[0]) . "<br>";
$subStrStart += strlen($tok);
$tok = strtok(", ");
}
?>
output:
PTR found more than 1 times, exaclty: 2
You are going to run into some issues with just using explode. In your example, if you use explode, you'll get:
'PTR', ' PTR', ' SDP', ' LTP'
You have to map trim in there.
<?php
// explode on , and remove spaces
$myArray = array_map('trim', explode(',', $str));
// get a count of all the values into a new array
$stringCount = array_count_values($myArray);
// sum of all the $stringCount values should equal size of $stringCount IE: they are all 1
$hasDupes = array_sum($stringCount) != count($stringCount);
?>

How do I echo a different statement when different checkboxes are selected with php? [duplicate]

I have searched everywhere but can't find a solution that works for me.
I have the following:
$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);
For this example lets say:
$studio = '1';
$one_bed = '3';
$two_bed = '3';
I then use the implode function to put a comma in between all the values:
$bedroom_list = implode(", ", array_filter($bedroom_array));
echo $bedroom_list;
This then outputs:
1, 2, 3
What I want to do is find the last comma in the string and replace it with an &, so it would read:
1, 2 & 3
The string will not always be this long, it can be shorter or longer, e.g. 1, 2, 3, 4 and so on. I have looked into using substr but am not sure if this will work for what I need?
Pop off the last element, implode the rest together then stick the last one back on.
$bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
$last = array_pop($bedroom_array);
$string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;
Convert & to the entity & if necessary.
if you have comma separated list of words you may use:
$keyword = "hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf, sdgdfg";
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $keyword);
echo $keyword;
it will output:
hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf & sdgdfg
A one-liner alternative, that will work for any size array ($b = $bedroom_array):
echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b);
strrpos finds the last occurrance of a specified string.
$str = '1, 2, 3';
$index = strrpos( $str, ',' );
if( $index !== FALSE )
$str[ $index ] = '&';
function fancy_implode($arr){
array_push($arr, implode(' and ', array_splice($arr, -2)));
return implode(', ', $arr);
}
I find this easier to read/understand and use
Does not modify the original array
Does not use regular expressions as those may fail if strings in the array contain commas, there could be a valid reason for that, something like this: array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
Delimiters don't have to be of the same length as with some of the other solutions
$bedroom_list = implode(", ", array_filter($bedroom_array));
$vars = $bedroom_list;
$last = strrchr($vars,",");
$last_ = str_replace(",","&",$last);
echo str_replace("$last","$last_",$vars);
<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>
Here's another way to do the replacement with a regular expression using a positive lookahead which doesn't require a backreference:
$bedroom_list = preg_replace('/,(?=[^,]*$)/',' &', implode(', ', $bedroom_array));

Get characters from the left until space then one more character after it

I want to get all of the text from the left and go until there is a space and then get one more character after the space.
example:
"Brian Spelling" would be "Brian S"
How can I do this in php?
In ASP the code looks like this:
strName1=left(strName1,InStr(strName1, " ")+1)
<?php
$strName1 = "Brian Spelling";
$strName1 = substr($strName1, 0, strpos($strName1, ' ')+2);
echo $strName1;
prints
Brian S
Find the index of the space with strpos
Extract the string from the beginning to that index + 2 with substr
Also consider how you might need to update your logic for names like:
H. G. Wells
Martin Luther King, Jr.
Cher
Split your string with explode function and substring the first character of the second part with substr function.
$explodedString = explode(" ", $strName1);
$newString = $explodedString[0] . " " . substr($explodedString[1], 1);
Regexp - makes sure it hits the second word with /U modifier (ungreedy).
$t = "Brian Spelling something else";
preg_match( "/(.*) ./Ui", $t, $r );
echo $r[0];
And you get "Brian S".
Try this below code
$name="Brian Lara"
$pattern = '/\w+\s[a-zA-Z]/';
preg_match($pattern,$name,$match);
echo $match[0];
Ouput
Brian L
$string = "Brian Spelling";
$element = explode(' ', $string);
$out = $element[0] . ' ' . $element[1]{0};
and just for fun to take Rob Hruska's answer under advisement you could do something like this:
$skip = array( 'jr.', 'jr', 'sr', 'sr.', 'md' );
$string = "Martin Luther King Jr.";
$element = explode(' ', $string);
$count = count( $element );
if( $count > 1)
{
$out = $element[0] . ' ';
$out .= ( in_array( strtolower( $element[ $count - 1 ] ), $skip ) )
? $element[ $count - 2 ]{0} : $element[ $count - 1 ]{0};
} else $out = $string;
echo $out;
-just edited so "Cher" will work too
Add any suffixes that you want to skip add to the $skip array

how to set a character betwen other characters in php

how to convert string sample 1 to sample 2 in PHP:
this string : 0510
after : 05:10
thanks
Without giving more info, there are hundreds of ways to convert '0510' to '05:10'. You can use .substr():
$string = '0510';
$string = substr($string, 0, 2).':'.substr($string, -2);
Or brackets:
$string = $string[0].$string[1].':'.$string[2].$string[3];
Or .str_split() with .implode():
$string = implode(':', str_split($string, 2));
Or .preg_replace():
$string = preg_replace(`~(\d{2})(\d{2})~`, '$1:$2', $string);
I'm not really sure about what you want but maybe you're looking for substr
$sample2 = substr($sample1, 0, 2) . ':' . substr($sample1, -2);
See http://php.net/manual/en/function.substr.php for more information.
As you added the "clock" tag, I assume you are talking about times. So you can use some date/time functions for this as well:
echo date("H:i", strtotime('0510'));
Output:
05:10
Use substr() to split the string into two and append them again.
$string = '0510';
$first = substr($string, 0, 2);
$second = substr($string, 2);
echo $first . ':' . $second

How to explode only on the last occurring delimiter?

$split_point = ' - ';
$string = 'this is my - string - and more';
How can I make a split using the second instance of $split_point and not the first one. Can I specify somehow a right to left search?
Basically how do I explode from right to left. I want to pick up only the last instance of " - ".
Result I need:
$item[0]='this is my - string';
$item[1]='and more';
and not:
$item[0]='this is my';
$item[1]='string - and more';
You may use strrev to reverse the string, and then reverse the results back:
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = array_map('strrev', explode($split_point, strrev($string)));
Not sure if this is the best solution though.
How about this:
$parts = explode($split_point, $string);
$last = array_pop($parts);
$item = array(implode($split_point, $parts), $last);
Not going to win any golf awards, but it shows intent and works well, I think.
Here is another way of doing it:
$split_point = ' - ';
$string = 'this is my - string - and more';
$stringpos = strrpos($string, $split_point, -1);
$finalstr = substr($string,0,$stringpos);
If I understand correctly, you want the example case to give you ('this is my - string', 'and more')?
Built-in split/explode seems to be forwards-only - you'll probably have to implement it yourself with strrpos. (right-left search)
$idx = strrpos($string, $split_point);
$parts = array(substr($string, 0, $idx), substr($string, $idx+strlen($split_point)))
Why not split on ' - ', but then join the first two array entries that you get back together?
I've stumbled uppon the same, and fixed it like so:
$split_point = ' - ';
$string = 'this is my - string - and more';
$reverse_explode = array_reverse(explode($split_point, $string));
I liked Moff's answer, but I improved it by limiting the number of elements to 2 and re-reversing the array:
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = array_reverse(array_map('strrev', explode($split_point, strrev($string),2)));
Then $result will be :
Array ( [0] => this is my - string [1] => and more )
this is my - string - and more
Use common explode function to get all strings
Get sizeof array and fetch last item
Pop last item using array_pop function.
Implode remaining string with same delimeter(if u want other delimeter can use).
Code
$arrSpits=explode("", "this is my - string - and more");
$arrSize=count($arrSpits);
echo "Last string".$arrSpits[arrSize-1];//Output: and more
array_pop(arrSpits); //now pop the last element from array
$firstString=implode("-", arrSpits);
echo "First String".firstString; //Output: this is my - string
I am underwhelmed by all of the over-engineered answers which are calling many functions and/or iterating over data multiple times. All of those string and array reversing functions make the technique very hard to comprehend.
Regex is powerfully elegant in this case. This is exactly how I would do it in a professional application:
Code: (Demo)
$string = 'this is my - string - and more';
var_export(preg_split('~.*\K - ~', $string));
Output:
array (
0 => 'this is my - string',
1 => 'and more',
)
By greedily matching characters (.*), then restarting the fullstring match (\K), then matching the last occurring delimiting substring (" - "), you are assured to only separate the final substring from the string.
Assuming you only want the first occurrence of $split_point to be ignored, this should work for you:
# retrieve first $split_point position
$first = strpos($string, $split_point);
# retrieve second $split_point positon
$second = strpos($string, $split_point, $first+strlen($split_point));
# extract from the second $split_point onwards (with $split_point)
$substr = substr($string, $second);
# explode $substr, first element should be empty
$array = explode($split_point, $substr);
# set first element as beginning of string to the second $split_point
$array[0] = substr_replace($string, '', strpos($string, $substr));
This will allow you to split on every occurrence of $split_point after (and including) the second occurrence of $split_point.
Just an idea:
function explode_reversed($delim,$s){
$result = array();
$w = "";
$l = 0;
for ($i = strlen($s)-1; $i>=0; $i-- ):
if ( $s[$i] == "$delim" ):
$l++;
$w = "";
else:
$w = $s[$i].$w;
endif;
$result[$l] = $w;
endfor;
return $result;
}
$arr = explode_reversed(" ","Hello! My name is John.");
print_r($arr);
Result:
Array
(
[0] => John.
[1] => is
[2] => name
[3] => My
[4] => Hello!
)
But this is much slower then explode. A test made:
$start_time = microtime(true);
for ($i=0; $i<1000;$i++)
$arr = explode_reversed(" ","Hello! My name is John.");
$time_elapsed_secs = microtime(true) - $start_time;
echo "time: $time_elapsed_secs s<br>";
Takes 0.0625 - 0.078125s
But
for ($i=0; $i<1000;$i++)
$arr = explode(" ","Hello! My name is John.");
Takes just 0.015625s
The fastest solution seems to be:
array_reverse(explode($your_delimiter, $your_string));
In a loop of 1000 times this is the best time I can get 0.03125s.
Not sure why no one posted a working function with $limit support though here it is for those who know that they'll be using this frequently:
<?php
function explode_right($boundary, $string, $limit)
{
return array_reverse(array_map('strrev', explode(strrev($boundary), strrev($string), $limit)));
}
$string = 'apple1orange1banana1cupuacu1cherimoya1mangosteen1durian';
echo $string.'<br /><pre>'.print_r(explode_right(1, $string, 3),1).'</pre>';
?>
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = end(explode($split_point, $string));
This is working fine

Categories