For example, if I have this string:
$stuff = "[1379082600-1379082720],[1379082480-1379082480],[1379514420-1379515800],";
I know can do this to split it into an array like this:
$stuff = str_replace(array("[","]"),array("",""),$stuff);
$stuff = explode(",",$stuff);
But it seems like there would be an easier way since the string is already in an array form almost. Is there an easier way?
since the string is already in an array form almost.
It is not. A string and an array are quite different things in terms of programming language.
Is there an easier way?
There is rather no point in looking for "an easier way". The way you have at the moment is pretty easy already.
You can get inside [] with preg_match_all. Try following:
preg_match_all("/\[(.*?)\]/",$stuff, $matches);
Output of $matches[1]
array (size=3)
0 => string '1379082600-1379082720' (length=21)
1 => string '1379082480-1379082480' (length=21)
2 => string '1379514420-1379515800' (length=21)
Trim the leading and trailing chars and then spit on ],[:
$stuff = explode('],[', trim($stuff, '[],');
This is as about as good as you're going to get I think
$stuff = array_filter(explode(",",str_replace(array("[","]"),"",$stuff)));
print_r($stuff);
[0] => 1379082600-1379082720
[1] => 1379082480-1379082480
[2] => 1379514420-1379515800
Using a regex-based solution will be slower / less efficient than the other methods.
If you are considering "simpler" to mean "fewer function calls, then I would recommend preg_split() or preg_match_all(). I want to explain, though, that preg_match_all() adds a variable to the global scope and preg_split() doesn't have to. Also, preg_match_all() produces a multidimensional array and you merely want a 1-dim array -- this is another advantage of preg_split().
Here is a battery of options. Some are mine and some are posted by others. Some work, some work better than others, and some don't work. It's education time...
$stuff = "[1379082600-1379082720],[1379082480-1379082480],[1379514420-1379515800],";
// NOTICE THE TRAILING COMMA ON THE STRING!
// my preg_split() pattern #1 (72 steps):
var_export(preg_split('/[\],[]+/', $stuff, 0, PREG_SPLIT_NO_EMPTY));
// my preg_split() pattern #2 (72 steps):
var_export(preg_split('/[^\d-]+/', $stuff, 0, PREG_SPLIT_NO_EMPTY));
// my preg_match_all pattern #1 (16 steps):
var_export(preg_match_all('/[\d-]+/', $stuff, $matches) ? $matches[0] : 'failed');
// my preg_match_all pattern #2 (16 steps):
var_export(preg_match_all('/[^\],[]+/', $stuff, $matches) ? $matches[0] : 'failed');
// Bora's preg_match_all pattern (144 steps):
var_export(preg_match_all('/\[(.*?)\]/', $stuff, $matches) ? $matches[0] : 'failed');
// Alex Howansky's is the cleanest, efficient / correct method
var_export(explode('],[', trim($stuff, '[],')));
// Andy Gee's method (flawed / incorrect -- 4 elements in output)
var_export(explode(",", str_replace(["[","]"], "", $stuff)));
// OP's method (flawed / incorrect -- 4 elements in output)
$stuff = str_replace(["[", "]"], ["", ""], $stuff);
$stuff = explode(",", $stuff);
var_export($stuff);
If you want to see the method demonstrations click here.
If you want to see the step counts click this pattern demonstration and swap in the patterns that I have provided.
Related
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 am trying to generate a regex that allows me to do the following:
I have a string containing several terms, all which are alphanumeric and maybe some of these special characters: +.#
They are separated by a comma as well.
This is kind of how it looks like:
$string = 'Term1,Term2,Term3,Term4'; ... And so on... (around 60 terms)
I want to be able to get each term and assign it to a variable, because I want to employ a second Regex to a long string, for example:
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
So pretty much I want to be able to check if any of the terms in the first string are present in the second string.
I watched the following tutorial:
https://www.youtube.com/watch?v=EkluES9Rvak
But I just seem to not be able to come up with something.
Thank you so much for your help in advance!
Cheers!
You can use array_intersect function after splitting strings into tokens:
$string = 'Term1,Term2,Term3,Term4';
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
$arr1 = explode(',', $string);
$arr2 = preg_split('/[,\h]+/', $secondString);
$arr = array_intersect(array_map('strtolower', $arr1), array_map('strtolower', $arr2));
print_r($arr);
Output:
Array
(
[0] => Term1
[1] => Term2
)
I'm using preg_replace to match and replace improperly encoded UTF-8 characters with their proper characters. I've created a "old" array containing the wrong characters, and a corresponding "new" array with the replacements. Here is a snippet of each array:
$old = array(
'/â€/',
'/’/',
);
$new = array(
'†',
'’',
);
(Note: If you're curious about why I'm doing this, read more here)
A sample string that may contain the wrong data could be:
The programmer’s becoming very frustrated
Which should become:
The programmer's becoming very frustrated
I'm using this function:
$result = preg_replace($old, $new, $str);
But the subject is actually becoming:
The programmer†™s becoming very frustrated
It's clear that PHP is doing what I call a non-greedy match on the subject (not the correct term to use here, I know). preg_replace is executing the replacement on the first pair in the old/new array without considering if there may a different pattern in the pattern array that is more appropriate. If I reverse the order of the replacement pair, then it works as expected.
My question is: Is there an approach that will allow preg_replace to consider all elements of the pattern array before executing a replacement, or is my only option to re-order the arrays?
I don't think there is any option like that. However, you could use an associative array to store your replacements and sort it using uasort and strlen, so larger matches would come first and you wouldn't need to manage your array order manually.
Then you can use array_keys and array_values to act just like your separated $old and $new arrays.
$replacements = array(
'†' => '/â€/',
'’' => '/’/',
);
// sorts the replacements array by value string length keeping the indexes intact
uasort($replacements, function($a, $b) {
return strlen($b) - strlen($a);
});
$str = 'The programmer’s becoming very frustrated';
$result = preg_replace(array_values($replacements), array_keys($replacements), $str);
EDIT: As #CasimiretHippolyte pointed out, using array_values is not necessary on the first parameter of the preg_replace function in this case. It would only return a copy from $replacements with numerical indexes but the order would be the same. Unless you need an array with identical structure to $old from your question, you do not need to use it.
Order the arrays $old and $new in such way that the longest regex becomes first:
$old = array(
'/’/',
'/â€/',
);
$new = array(
'’',
'†',
);
$str = 'The programmer’s becoming very frustrated';
$result = preg_replace($old, $new, $str);
echo $result,"\n";
output:
The programmer’s becoming very frustrated
I don't believe there is a way to do this only using preg_replace. However you can easily do this sorting your array beforehand:
$replacements = array_combine($old, $new);
krsort($replacements);
$result = preg_repalce( array_keys($replacements), array_values($replacements), $string);
Background
I have an array which I create by splitting a string based on every occurrence of 0d0a using preg_split('/(?<=0d0a)(?!$)/').
For example:
$string = "78781110d0a78782220d0a";
will be split into:
Array ( [0] => 78781110d0a [1] => 78782220d0a )
A valid array element has to start with 7878 and end with 0d0a.
The Problem
But sometimes, there's an additional 0d0a in the string which splits into an extra and invalid array element, i.e., that doesn't begin with 7878.
Take this string for example:
$string = "78781110d0a2220d0a78783330d0a";
This is split into:
Array ( [0] => 78781110d0a [1] => 2220d0a [2] => 78783330d0a )
But it should actually be:
Array ( [0] => 78781110d0a2220d0a [1] => 78783330d0a)
My Solution
I've written the following (messy) code to get around this:
$data = Array('78781110d0a','2220d0a','78783330d0a');
$i = 0; //count for $data array;
$j = 0; //count for $dataFixed array;
$dataFixed = $data;
foreach($data as $packet) {
if (substr($packet,0,4) != "7878") { //if packet doesn't start with 7878, do some fixing
if ($i != 0) { //its the first packet, can't help it!
$j++;
if ((substr(strtolower($packet), -4, 4) == "0d0a")) { //if the packet doesn't end with 0d0a, its 'mostly' not valid, so discard it
$dataFixed[$i-$j] = $dataFixed[$i-$j] . $packet;
}
unset($dataFixed[$i-$j+1]);
$dataFixed = array_values($dataFixed);
}
}
$i++;
}
Description
I first copy the array to another array $dataFixed. In a foreach loop of the $data array, I check whether it starts with 7878. If it doesn't, I join it with the previous array in $data. I then unset the current array in $dataFixed and reset the array elements with array_values.
But I'm not very confident about this solution.. Is there a better, more efficient way?
UPDATE
What if the input string doesn't end in 0d0a like its supposed to? It will stick to the previous array element..
For e.g.: in the string 78781110d0a2220d0a78783330d0a0000, 0000 should be separated as another array element.
Use another positive lookahead (?=7878) to form:
preg_split('/(?<=0d0a)(?=7878)/',$string)
Note: I removed (?!$) because I wasn't sure what that was for, based on your example data.
For example, this code:
$string = "78781110d0a2220d0a78783330d0a";
$array = preg_split('/(?<=0d0a)(?=7878)(?!$)/',$string);
print_r($array);
Results in:
Array ( [0] => 78781110d0a2220d0a [1] => 78783330d0a )
UPDATE:
Based on your revised question of having possible random characters at the end of the input string, you can add three lines to make a complete program of:
$string = "78781110d0a2220d0a787830d0a330d0a0000";
$array = preg_split('/(?<=0d0a)(?=7878)/',$string);
$temp = preg_split('/(7878.*0d0a)/',$array[count($array)-1],null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$array[count($array)-1] = $temp[0];
if(count($temp)>1) { $array[] = $temp[1]; }
print_r($array);
We basically do the initial splitting, then split the last element of the resulting array by the expected data format, keeping the delimiter using PREG_SPLIT_DELIM_CAPTURE. The PREG_SPLIT_NO_EMPTY ensures we won't get an empty array element if the input string doesn't end in random characters.
UPDATE 2:
Based on your comment below where it seems you're implying there might be random characters between any of the desired matches, and you want these random characters preserved, you could do this:
$string = "0078781110d0a2220d0a2220d0a0000787830d0a330d0a000078781110d0a2220d0a0000787830d0a330d0a0000";
$split1 = preg_split('/(7878.*?0d0a)/',$string,null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$result = array();
foreach($split1 as $e){
$split2 = preg_split('/(.*0d0a)/',$e,null,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
foreach($split2 as $el){
// test if $el doesn't start with 7878 and ends with 0d0a
if(strpos($el,'7878') !== 0 && substr($el,-4) == '0d0a'){
//if(preg_match('/^(?!7878).*0d0a$/',$el) === 1){
$result[ count($result)-1 ] = $result[ count($result)-1 ] . $el;
} else {
$result[] = $el;
}
}
}
print_r($result);
The strategy employed here is different than above. First we split the input string based on the delimiter that matches your desired data, using the nongreedy regex .*?. At this point we have some strings that contain the ending of a desired value and some garbage at the end, so we split again based on the last occurrence of "0d0a" with the greedy regex .*0d0a. We then append any of those resulting values that don't start with "7878" but end with "0d0a" to the previous value, as this should repair the first and second halves that got split because it contained an extra "0d0a".
I provided two methods for the innermost if statement, one using regular expressions. The regex one is marginally slower in my testing, so I've left that one commented out.
I might still not have your full requirements, so you'll have to let me know if it works and perhaps provided your full dataset.
I think you are using a delimiter "0d0a" which also happens to be part of a content! Its not possible to avoid getting junk data as long as delimiter can also be part of content. Somehow delimiter must be unique.
Possible solutions.
Change the delimited to something else that doesn't occur as part of your data ( 000000, #!.;)
If you are definite about length of text that easy arrange item may have, use it. As per examples its not possible.
Solutions given in answers considering only sample data you have shared. If you are confidant about what will be the content of string, then these solutions given by others are pretty good to use. Otherwise these solutions wont assure you guarantee!
Best solution: Fix right delimiter then use regex or explode whatever you prefer.
Why don't you use preg_match_all instead? You can avoid all of the non-capturing groups (the look aheads, look behinds) in order to split the string (which without the non-capturing groups removes the matches), and just find the matches you're looking for:
Updated
<?php
$string = "00787817878110d0a22278780d0a78783330d0a00";
preg_match_all('/7878.*?0d0a(?=7878|[^(7878)]*?$)/', $string, $arr);
print_r($arr);
?>
Gives an array $arr[0] => ( [0] => 787817878110d0a22278780d0a, [1] => 78783330d0a ). Strips leading and trailing garbage characters (whatever doesn't start with 7878 or end with 7878 or 0d0a.
So $arr[0] would be the array of values that you are looking for.
See example on ideone
Works with multiple 7878 values and multiple 0d0a values (even though that's ridiculous).
Update
If splitting is more your style, why not avoid regular expressions altogether?
<?php
$string = "787817878110d0a22278780d0a78783330d0a";
$arr = explode('0d0a7878', $string);
$string = implode('0d0a,7878', $arr);
$arr = explode(',', $string);
print_r($arr);
?>
Here we split the string by the delimiter 0d0a7878, which is what #CharlieGorichanaz's solution is doing, and props to him for the quick, accurate solution. We then add a comma, because who doesn't love comma separated values? And we explode again on the commas for an array of desired values. Performance-wise, this ought to be faster than using regular expressions. See example.