I have a string variable in php, with look like "0+1.65+0.002-23.9", and I want to split in their individual values.
Ex:
0
1.65
0.002
-23.9
I Try to do with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work I expected.
Can anyone help me out? Thanks a lot in advance.
Like this:
$yourstring = "0+1.65+0.002-23.9";
$regex = '~\+|(?=-)~';
$splits = preg_split($regex, $yourstring);
print_r($splits);
Output (see live php demo):
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
Explanation
Our regex is +|(?=-). We will split on whatever it matches
It matches +, OR |...
the lookahead (?=-) matches a position where the next character is a -, allowing us to keep the -
Then we split!
Option 2 if you decide you also want to keep the + Character
(?=[+-])
This regex is one lookahead that asserts that the next position is either a plus or a minus. For my sense of esthetics it's quite a nice solution to look at. :)
Output (see online demo):
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
Reference
Lookahead and Lookbehind Zero-Length Assertions
Mastering Lookahead and Lookbehind
You could try this
$data = ' 0 1.65 0.002 -23.9';
$t = str_replace( array(' ', ' -'), array(',',',-'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
Which gives you an array containing each field like so:
Array
(
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
)
RE: Your comment: The originals values are in a string variable only separated for a sign possitive or negative
$data = ' 0+1.65+0.002-23.9 ';
$t = str_replace( array('-', '+'), array(',-',',+'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
which gives a similiar answer but with the correct inputs and outputs
Array
(
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
)
Related
After instructing clients to input only
number comma number comma number
(no set length, but generally < 10), the results of their input have been, erm, unpredictable.
Given the following example input:
3,6 ,bannana,5,,*,
How could I most simply, and reliably end up with:
3,6,5
So far I am trying a combination:
$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma
But before I keep throwing things at it...is there an elegant way, probably from a regex boffin!
In a purely abstract sense this is what I'd do:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
Example:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>
Here's an example using regex,
$string = '3,6 ,bannana,5,-6,*,';
preg_match_all('#(-?[0-9]+)#',$string,$matches);
print_r($matches);
will output
Array
(
[0] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
[1] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
)
Use $matches[0] and you should be on your way.
If you don't need negative numbers just remove the first bit in the in the regex rule.
So I'm using the next thing:
<?php
$string='JUD. NEAMT, SAT ROMEDC ALEXANDRE COM. COMENKA, STR. EXAMMS RANTEM, NR.6';
$result=preg_split("/(?:JUD.\s*|\s*SAT\s*|\s*COM\.\s*|\s*STR.\s*|\s*SECTOR\s*|\s*B-DUL\s*|\s*NR\.\s*|\s*ET.\s*|\s*MUN\.\s*|\s*BL.\s*|\s*SC\.\s*|\s*AP\.\s*)/", $string);
array_walk($result,function($value,$key) use (&$result){
if(stristr($value, ","))
{
$result[$key]=explode(",", $value)[0];
}
});
print_r(array_filter($result));
the output would be:
Array
(
[1] => NEAMT
[2] => ROMEDC ALEXANDRE
[3] => COMENKA
[4] => EXAMMS RANTEM
[5] => 6
)
The main problem is that $string is different each time and can contain different parameters like 'SAT' could simply not appear in another string because is replaced by 'SECTOR'.
All these are localization words like House number('NR.') or Town name('JUD').
What I want is to convert the above array into something like this:
Array
(
['JUD'] => NEAMT
['SAT'] => ROMEDC ALEXANDRE
['COM'] => COMENKA
['STR'] => EXAMMS RANTEM
['NR'] => 6
)
I hope you got the idea:
I'm getting from a string 'address' different parameters like apartment number , building number and so on (it depends each time on the customer-- he might be living at a house so there is no apartment number) so having words instead of numbers in the array would help me output the info in different columns.
Any idea is welcome.
Thank you.
$string='JUD. NEAMT, SAT ROMEDC ALEXANDRE COM. COMENKA, STR. EXAMMS RANTEM, NR.6';
//fix missing commas
$string = preg_replace('#([A-Z]+) ([A-Z]+\.)#',"$1, $2",$string);
//a trick to fix non space on `NR.6`
$string = str_replace(['.',' '],['. ',' '],$string);
//get the part seperated by comma, trim to remove spaces
$ex = array_map('trim',explode(',',$string));
//iterate over it
foreach($ex as $e){
//explode the part by space
$new = array_map('trim',explode(' ',$e));
//take the first part as key, remove spaces and dot
$key = trim(array_shift($new),' . ');
//collect via key and implode rest with a space
$coll[$key]=implode(' ',$new);
}
//done
print_r($coll);
Result:
Array
(
[JUD] => NEAMT
[SAT] => ROMEDC ALEXANDRE
[COM] => COMENKA
[STR] => EXAMMS RANTEM
[NR] => 6
)
a fast lane to rome...
My situation is: I'm processing an array word by word. What I'm hoping to do and
working on, is to capture a certain word. But for that I need to test two patterns or more with preg-match.
This is my code :
function search_array($array)
{
$pattern = '[A-Z]{1,3}[0-9]{1,3}[A-Z]{1,2}[0-9]{1,2}[A-Z]?';
$pattern2 = '[A-Z]{1,7}[0-9]{1,2}';
$patterns = array($pattern, $pattern2);
$regex = '/(' .implode('|', $patterns) .')/i';
foreach ($array as $str) {
if (preg_match ($regex, $str, $m)){
$matches[] = $m[1];
return $matches[0];
}
}
}
Example of array I could have :
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => XXXX [4] => ABC01DC4 )
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => ABCDEF4 [4] => XXXX [5] => XX )
Words I would like to catch :
-In the first array : ABC01DC4
-In the second array : ABCDEF4
The problem is not the pattern itself, it's the syntax to use multiple pattern in the same pregmatch
Your code worked with me, and I didn't find any problem with the code or the REGEX. Furthermore, the description you provided is not enough to understand your needs.
However, I have guessed one problem after observing your code, which is, you didn't use any anchor(^...$) to perform matching the whole string. Your regex can find match for these inputs: %ABC01DC4V or ABCDEF4EE. So change this line with your code:
$regex = '/^(' .implode('|', $patterns) .')$/i';
-+- -+-
I'm processing a single string which contains many pairs of data. Each pair is separated by a ; sign. Each pair contains a number and a string, separated by an = sign.
I thought it would be easy to process, but i've found that the string half of the pair can contain the = and ; sign, making simple splitting unreliable.
Here is an example of a problematic string:
123=one; two;45=three=four;6=five;
For this to be processed correctly I need to split it up into an array that looks like this:
'123', 'one; two'
'45', 'three=four'
'6', 'five'
I'm at a bit of dead end so any help is appreciated.
UPDATE:
Thanks to everyone for the help, this is where I am so far:
$input = '123=east; 456=west';
// split matches into array
preg_match_all('~(\d+)=(.*?);(?=\s*(?:\d|$))~', $input, $matches);
$newArray = array();
// extract the relevant data
for ($i = 0; $i < count($matches[2]); $i++) {
$type = $matches[2][$i];
$price = $matches[1][$i];
// add each key-value pair to the new array
$newArray[$i] = array(
'type' => "$type",
'price' => "$price"
);
}
Which outputs
Array
(
[0] => Array
(
[type] => east
[price] => 123
)
)
The second item is missing as it doesn't have a semicolon on the end, i'm not sure how to fix that.
I've now realised that the numeric part of the pair sometimes contains a decimal point, and that the last string pair does not have a semicolon after it. Any hints would be appreciated as i'm not having much luck.
Here is the updated string taking into account the things I missed in my initial question (sorry):
12.30=one; two;45=three=four;600.00=five
You need a look-ahead assertion for this; the look-ahead matches if a ; is followed by a digit or the end of your string:
$s = '12.30=one; two;45=three=four;600.00=five';
preg_match_all('/(\d+(?:.\d+)?)=(.+?)(?=(;\d|$))/', $s, $matches);
print_r(array_combine($matches[1], $matches[2]));
Output:
Array
(
[12.30] => one; two
[45] => three=four
[600.00] => five
)
I think this is the regex you want:
\s*(\d+)\s*=(.*?);(?=\s*(?:\d|$))
The trick is to consider only the semicolon that's followed by a digit as the end of a match. That's what the lookahead at the end is for.
You can see a detailed visualization on www.debuggex.com.
You can use following preg_match_all code to capture that:
$str = '123=one; two;45=three=four;6=five;';
if (preg_match_all('~(\d+)=(.+?);(?=\d|$)~', $str, $arr))
print_r($arr);
Live Demo: http://ideone.com/MG3BaO
$str = '123=one; two;45=three=four;6=five;';
preg_match_all('/(\d+)=([a-zA-z ;=]+)/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
o/p:
Array
(
[0] => Array
(
[0] => 123=one; two;
[1] => 45=three=four;
[2] => 6=five;
)
[1] => Array
(
[0] => 123
[1] => 45
[2] => 6
)
[2] => Array
(
[0] => one; two;
[1] => three=four;
[2] => five;
)
)
then y can combine
echo '<pre>';
print_r(array_combine($matches[1],$matches[2]));
echo '</pre>';
o/p:
Array
(
[123] => one; two;
[45] => three=four;
[6] => five;
)
Try this but this code is written in c#, you can change it into php
string[] res = Regex.Split("123=one; two;45=three=four;6=five;", #";(?=\d)");
--SJ
Hi I need a preg_split regex that will split a string at substrings in square brackets.
This example input:
$string = 'I have a string containing [substrings] in [brackets].';
should provide this array output:
[0]= 'I have a string containing '
[1]= '[substrings]'
[2]= ' in '
[3]= '[brackets]'
[4]= '.'
After reading your revised question:
This might be what you want:
$string = 'I have a string containing [substrings] in [brackets].';
preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
You should get:
Array
(
[0] => I have a string containing
[1] => [substrings]
[2] => in
[3] => [brackets]
[4] => .
)
Original answer:
preg_split('/%+/i', 'ot limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
You should get:
Array
(
[0] => ot limited to 3
[1] => so it can be
[2] => or
[3] => or
[4] => , etc Tha
)
Or if you want a mimimum of 3 then try:
preg_split('/%%%+/i', 'Not limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
Have a go at http://regex.larsolavtorvik.com/
I think this is what you are looking for:
$array = preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);