I have an integer $client_version=1000 I do need to add dots between every number in this integer so it looks like 1.0.0.0 and save it in new variable as string.
How can I do this?
Easy enough:
$client_version = 1000;
$dotted = join(".",str_split($client_version));
Note that this will always split it so that there is only one character between the dots. If you want something like 1.00.0, you'll need to change your question to explain more about what you're trying to do and what patterns you need.
PHP offers the function array str_split ( string $string [, int $split_length = 1 ] ) to convert a string to a character-array or blocks of characters.
In your case, invoking str_split((string)1000, 1) or str_split((string)1000) will result in:
Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
)
Code:
implode('.',str_split((string)1000))
Result: 1.0.0.0
For a more general, yet less well known approach, based on Regular Expression see this gist and this tangentially related topic on SO.
Code:
preg_match_all('/(.{1})/', (string)1000, $matches);
echo implode('.', $matches[0]);
Result: 1.0.0.0
Use str_split to get an array of chars and then implode them.
$client_version = 1000;
$client_version_chars = str_split($client_version);
$client_version_with_dots = implode('.', $client_version_chars);
Related
Given the following code :
$str = 'CLAX';
echo $str[2]; //prints 'A'
then why should I use str_split( $str ) to convert string to a array of characters ?
I understand str_split( $str , 2 ) will return array of strings; each string being 2 characters long.
http://php.net/manual/en/function.str-split.php
This function is to split a string into an array with given string split length
By default string split length is set 1
If you want to split a string into given in given length, then you can use str_split. But in your case you are splitting string with default length 1 that is by you are getting confused.
<?php
$str = "CLAX";
echo $str[2]; //here you are referring to 2 index of string
$arr2 = str_split($str);
Array
(
[0] => C
[1] => L
[2] => A
[3] => X
)
echo $str[2]; //here you are referring to 2 index of an array
str_split reference
<?php
$str = "Hello Friend";
$arr2 = str_split($str, 3);
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Using str_split() comes in pretty handy when you want to leverage array functions to perform a task on the components in a string.
str_split() works like explode() except it doesn't care what the characters are, just their position in the string -- there are specific use cases for this.
Use Case #1: Group Array Elements by Letter Range
Rather than manually declaring an array with 3 letters per element, like this:
$chunks=['ABC','DEF','GHI','JKL','MNO','PQR','STU','VWX','YZ']
The same array can be produced with:
$chunks=str_split(implode(range('A','Z')),3);
This purely for demonstration. Of course, declaring it manually would be more efficient. The potential benefit for other cases is code flexibility and ease of code modification.
Use Case #2: Convert string to array at different character occurence
Use str_split() when using a foreach loop to process each character.
$string="abbbaaaaaabbbb";
$array=str_split($string);
$last="";
foreach($array as $v){
if(!$last || strpos($last,$v)!==false){
$last.=$v;
}else{
$result[]=$last;
$last=$v;
}
}
$result[]=$last;
var_export($result);
If you try to supply the foreach loop with $string php will choke on it. str_split() is the right tool for this job.
Use Case #3: Find element of an array those contains only specific character set in PHP
Use str_split() to in association with other array functions to check values in a way that string functions are not well suited for.
[I'll refrain from transferring the full code block across.]
I want to extract the dimension from this given string.
$str = "enough for hitting practice. The dimension is 20'X10' *where";
I expect 20'X10' as the result.
I tried with the following code to get the number before and after the string 'X. But it is returning an empty array.
$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X\b((?:\W*\w+){0,1})/i';
preg_match_all ($regexForMinimumPattern, $str, $minimumPatternMatches);
print_r($minimumPatternMatches);
Can anyone please help me to fix this? Thanks in advance.
Just remove the \b from your pattern (and append a \' in the end if you want the trailing quote):
$regexForMinimumPattern ='/((?:\w+\W*){0,1})\'X((?:\W*\w+){0,1})\'/i';
NB: \b is the meta-character for word-boundaries, you don't need it here.
Assuming that the format of the string we want is 00'X00 :
$regexForMinimumPattern ='/[0-9]{1,2}\'X[0-9]{1,2}/i';
this gives you a result like
Array ( [0] => Array ( [0] => 20'X10 ) )
So: can a simple preg_replace()do that? Perhaps...
<?php
$str = "enough for hitting practice. The dimension is 20'X10' *where";
$dim = preg_replace("#(.*?)(\d*?)(\.\d*)?(')(X)(\d*?)(\.\d*)?(')(.+)#i","$2$3$4$5$6$7", $str);
var_dump($dim); //<== YIELDS::: string '20'X10' (length=6)
You may try it out Here.
Am I correct that character precedence would order these like this:
1--2016 name.png, 11--2017 name.png, 2--1999 name.png
Numerically, however, they would be like this:
1--2016 name.png, 2--1999 name.png, 11--2017 name.png
That is, if I'm looking at the first numbers alone. How do you numerically sort an array with strings like this? Namely, integers appended with "--".
It's important to note that these "strings" are actually pathnames which cannot be renamed. See glob for more information.
Edit, after modified question:
After your edit, obviously all answers in this thread are wrong. Also, you don't have to only copy-and-paste a piece of code, but to read entire answer. Sure enough, in my original answer, I say:
if you have a value like “12--3”, it will be sorted like “123”
So, you could see right away that your real case is not coherent with provided sample.
This second solution will sort an array by number at start of given basename path followed by two dashes. It will be applicable on following cases:
String Will be sorted by
------------------------------ -----------------
/Absolute/Path/12-- 12
/Absolute/Path/12--2001.png 12
/12--2001.png 12
12--2001.png 12
a12--2001.png a12--2001.png
-12--2001.png -12--2001.png
Having this array:
[
'/path/to/image/1--2016 name.png',
'/path/to/image/11--2017.png',
'/path/to/image/2--1999.png'
]
You can replace regular expression patter of above original solution with this pattern:
~^(.*/)?(\d+)--[^/]*$~
And above array will be sorted in this way:
Array
(
[0] => /path/to/image/1--2016 name.png
[1] => /path/to/image/2--1999.png
[2] => /path/to/image/11--2017.png
)
eval.in demo
Pattern explanation:
~
^ # Start of string
(.*/)? # Group 1 (optional): zero-ore-more characters followed by a slash
(\d+) # Group 2: one-or-more digits
-- # two dashes
[^/]* # zero-or-more characters, except slash
$ # End of string
~
In the future, take a look at How to create a Minimal, Complete, and Verifiable example
Original answer (for original question):
There are surely many ways to obtain your result. Using usort and preg_replace:
$array = ['11--','23--','1--'];
usort
(
$array,
function( $a, $b )
{
return preg_replace( '~[^\d]~', '', $a ) - preg_replace( '~[^\d]~', '', $b );
}
);
$array now is:
Array
(
[0] => 1--
[1] => 11--
[2] => 23--
)
Above solution will sort your array deleting1 all not digits characters.
So, if you have a value like 12--3, it will be sorted like 123. Consequently, it doesn't work on not-integer or negative numbers.
1 Actually, the original array values are not changed.
If you wanted a quick fix to getting this done, you could:
$strings = array('5--', '2--', '11--');
$newStrings = array();
foreach ($strings as $string) {
$stringNew = str_replace('--', '', $string);
array_push($newStrings, $stringNew);
}
sort($newStrings);
$doneArray = array();
foreach ($newStrings as $newString) {
array_push($doneArray, $newString.'--');
}
// $doneArray is the new array full of the sorted strings.
I didn't really bother with the variable names, but that's a nice way to do it.
natsort
See here.
I'm not sure how glob sorts things as they come in, but I thought that sort would have ordered them correctly, but natsort will do the trick.
I have bunch of strings like this:
a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc
And what I need to do is to split them up based on the hashtag position to something like this:
Array
(
[0] => A
[1] => AAX1AAY222
[2] => B
[3] => BBX4BBY555BBZ6
[4] => C
[5] => MMM1
[6] => D
[7] => ARA1
[8] => E
[9] => ABC
)
So, as you see the character right behind the hashtag is captured plus everything after the hashtag just right before the next char+hashtag.
I've the following RegEx which works fine only when I have a numeric value in the end of each part.
Here is the RegEx set up:
preg_split('/([A-Z])+#/', $text, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
And it works fine with something like this:
C#mmm1D#ara1
But, if I change it to this (removing the numbers):
C#mmmD#ara
Then it will be the result, which is not good:
Array
(
[0] => C
[1] => D
)
I've looked at this question and this one also, which are similar but none of them worked for me.
So, my question is why does it work only if it has followed by a number? and how I can solve it?
Here you can see some of them sample strings which I have:
a#123b#abcc#def456 // A:123, B:ABC, C:DEF456
a#abc1def2efg3b#abcdefc#8 // A:ABC1DEF2EFG3, B:ABCDEF, C:8
a#abcdef123b#5c#xyz789 // A:ABCDEF123, B:5, C:XYZ789
P.S. Strings are case-insensitive.
P.P.S. If you ever thinking what the hell are these strings, they are user submitted answers to a questionnaire, and I can't do anything on them like refactoring as they are already stored and just need to be proceed.
Why Not Using explode?
If you look at my examples you will see that I need to capture the character right before the # as well. If you think it's possible with explode() please post the output as well, thanks!
Update
Should we focus on why /([A-Z])+#/ works only if numbers included? thanks.
Instead of using preg_split(), decide what you want to match instead:
A set of "words" if followed by either <any-char># or <end-of-string>.
A character if immediately followed by #.
$str = 'a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc';
preg_match_all('/\w+(?=.#|$)|\w(?=#)/', $str, $matches);
Demo
This expression uses two look-ahead assertions. The results are in $matches[0].
Update
Another way of looking at it would be this:
preg_match_all('/(\w)#(\w+)(?=\w#|$)/', $str, $matches);
print_r(array_combine($matches[1], $matches[2]));
Each entry starts with a single character, followed by a hash, followed by X characters until either the end of the string is encountered or the start of a next entry.
The output is this:
Array
(
[a] => aax1aay222
[b] => bbx4bby555bbz6
[c] => mmm1
[d] => ara1
[e] => abc
)
If you still want to use preg_split you can remove the + and it might work as expected:
'/([A-Z])#/i'
Since then you only match the hashtag and ONE alpha character before, and not all them.
Example: http://codepad.viper-7.com/z1kFDb
Edit: Added a case-insensitive flag i in the pattern.
Use explode() rather than Regexp
$tmpArray = explode("#","a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc");
$myArray = array();
for($i = 0; $i < count($tmpArray) - 1; $i++) {
if (substr($tmpArray[$i],0,-1)) $myArray[] = substr($tmpArray[$i],0,-1);
if (substr($tmpArray[$i],-1)) $myArray[] = substr($tmpArray[$i],-1);
}
if (count($tmpArray) && $tmpArray[count($tmpArray) - 1]) $myArray[] = $tmpArray[count($tmpArray) - 1];
edit: I updated my answer to reflect better reading the questions
You can use explode() function that will split the string except the hash signs, like stated in the answers given before.
$myArray = explode("#",$string);
For the string 'a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc' this returns something like
$myarray = array('a', 'aax1aay22b', 'bbx4bby555bbz6c' ....);
All you need now is to take the last character of each string in array as another item.
$copy = array();
foreach($myArray as $item){
$beginning = substr($item,0,strlen($item)-1); // this takes all characters except the last one
$ending = substr($item,-1); // this takes the last one
$copy[] = $beginning;
$copy[] = $ending;
} // end foreach
This is an example, not tested.
EDIT
Instead of substr($item,0,strlen($item)-1); you might use substr($item,0,-1);.
How could I Separate characters and numbers from an input and store as separate variables php for example my input string is as $str="abc567" and i need to separate it as $str1="abc" and $str2="567".
You can use preg_split using lookahead and lookbehind:
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "abc567"));
prints
Array
(
[0] => abc
[1] => 567
)
I hope this helps :)
Regards.
By using preg_split, you can pass a regex string. This will return all the patterns that match a given regex string, and you can use that to store the various values into their respective variables.
Notice there is no code here; you should be trying to work these things out yourself.
well preg_split will help you.
Official Document : http://php.net/manual/en/function.preg-split.php
Example
echo "<pre>";
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "abc567"));
echo "</pre>";
above will out put.
Array
(
[0] => abc
[1] => 567
)
try this
$str="abc567";
preg_match_all('/(\d)|(\w)/', $str, $matches);
$numbers = implode($matches[1]);
$characters = implode($matches[2]);
If your are wanting all numbers and all letters in separate variables you can use:
$your_var = "abc567";
$str_letters = preg_replace('/[a-z]/', "", $your_var);
$str_numbers = preg_replace('/[0-9]/', "", $your_var);
Beware that if $your_var = abc7567d64h num = 756764 letters = abcdh