sorry for a noob question but I am wondering if you could format strings in php with comma or dashes, something like this:
Ex. #1
Sample Input: 123456789
Formatted Output: 123,456,789 or 123-456-789
Ex. #2
Sample Input: 0123456789
Formatted Output: 012,3456,789 or 012-3456-789
If anyone could help me out, that would be appreciated.
You could use a regex replacement here:
function formatNum($input, $sep) {
return preg_replace("/^(\d{3})(\d+)(\d{3})$/", "$1".$sep."$2".$sep."$3", $input);
}
echo formatNum("123456789", ","); // 123,456,789
echo "\n";
echo formatNum("0123456789", "-"); // 012-3456-789
If it's just a case of split the initial string into 3 char segments and join them with a specific char, you can use str_split() with the number of chars you want in each segment and then implode() the result with the separator you need...
$test = '012345678';
echo implode("-", str_split($test, 3));
$number = 133456789;
$number_text = (string)$number; // convert into a string
if(strlen($number_text) %3 == 0){
$arr = str_split($number_text, "3");
// $price_new_text = implode(",", $arr);
$number_new_text = implode("-", $arr);
echo $number_new_text;
}
else{
if( preg_match( '/(\d{3})(\d{4})(\d{3})$/', $number_text, $matches ) )
{
$number_new_text = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
$number_new_text = $matches[1] . ',' .$matches[2] . ',' . $matches[3];
echo $number_new_text;
}
}
Related
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);
?>
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));
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
I have E-20-99 in a string i want to get last value 99 and add 1 means 100 and then wants to generate new string E-20-100.
If your string ALWAYS looks like this, you can easily break it without a regex, simply by using explode()
$string = "E-20-99";
$parts = explode('-', $string);
$last_part = $parts[2] + 1;
$parts[2] = $last_part;
$string = implode('-', $parts);
echo $string;
If the string is always E-20-XX you can use
$n = ((int)substr('E-20-99', strlen('E-20-')))+1;
echo 'E-20-' . $n;
If the string might vary a bit more you could use a regualar expressions such as:
$string = 'E-20-99';
preg_match('/(E-\d+-)(\d+)/', $string, $match);
echo $match[1] . ((int)$match[2] + 1);
$old_str = 'E-20-99';
$new_str = preg_replace_callback('/(?<=-)\d+$/', function($matches) {
return $matches[0] + 1;
}, $old_str);
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));