i need your help again ;-)
How can i extract ids from given string:
",object|1301,object|5419,object|5364,"
Can it solved by a regular expression?
Thank for answers
A Regex Method: Demo
$in = ",object|1301,object|5419,object|5364,";
var_export(preg_split('/\D+/', $in, 0, PREG_SPLIT_NO_EMPTY));
Output:
array (
0 => '1301',
1 => '5419',
2 => '5364',
)
A non-regex method (there will be many ways to do this):
$in=",object|1301,object|5419,object|5364,";
var_export(array_filter(explode(',object|', rtrim($in, ',')), 'strlen'));
(same output)
A preg_match_all() method:
$in = ",object|1301,object|5419,object|5364,";
var_export(preg_match_all('/\K\d+/', $in, $out) ? $out[0] : []);
(same output)
--
Another non-regex method:
$in = ",object|1301,object|5419,object|5364,";
var_export(explode('|', ltrim(str_replace(',object', '', $in), '|')));
(same output)
Use the pattern ([0-9]+) to get the numbers from the string.
Example: https://regex101.com/r/6Unuvt/1/
Related
My input string:
Yth. ErzaPay.com (DS008206). Sal:465.670, Dlm proses:0. Pemakaian hr
ini:126.885 Komisi:0 #*IDN1,IDN3 Open harga naik
How can I get the string value 465.670 ?
If this is a fairly strict format then you can use explode to get the value.
Other option it to use regex.
$temp = explode("Sal:",$str);
$sal = explode(",", $temp[1])[0];
echo $sal; //465.670
https://3v4l.org/Z6GfF
$string = "Yth. ErzaPay.com (DS008206). Sal:465.670, Dlm proses:0. Pemakaian hr ini:126.885 Komisi:0 #*IDN1,IDN3 Open harga naik";
$matches = [];
preg_match_all('/(\w+):([\.\d]+)/', $string, $matches);
// var_dump($matches);
$matches = [];
preg_match_all('/Sal:([\.\d]+)/', $string, $matches);
// var_dump($matches);
var_dump($matches[1][0]);
I prefer preg_match() for this task. It is cleanest to match the identifying substring, then reset the full string match with \K, then match 1 or more characters that are not a comma. Job done.
Using preg_match_all() to extract a single string makes no logical sense.
I prefer not to make successive explosions because it is generating arrays on the way to isolating a substring. In other words, it is simply indirect. If you are going to use explode() to hack a string into smaller chunks while searching for a solitary substring, use the third parameter of 2 so that php doesn't carry on looking for more delimiters to explode on.
strstr() with a true third parameter extracts the portion of a substring before a first encountered substring, so this can be used instead of a second explode() call.
I could go on list other whacky techniques, but at the end of the day, regex affords a direct and concise solution, so I would likely use preg_match() in my production code.
You were not clear about how your input strings may vary. I have only provided techniques suitable for your exact input.
Codes: (Demo)
$input = 'Yth. ErzaPay.com (DS008206). Sal:465.670, Dlm proses:0. Pemakaian hr ini:126.885 Komisi:0 #*IDN1,IDN3 Open harga naik';
echo preg_match('~Sal:\K[^,]+~', $input, $out) ? $out[0] : 'no match';
echo "\n---\n";
echo preg_replace('~^.*?Sal:|,.*?$~', '', $input);
echo "\n---\n";
echo strstr(explode('Sal:', $input, 2)[1], ',', true);
echo "\n---\n";
echo explode(',', explode('Sal:', $input, 2)[1], 2)[0];
echo "\n---\n";
if (($startPos = strpos($input, 'Sal:')) !== false && ($endPos = strpos($input, ',', $startPos)) !== false) {
$substrPos = $startPos + 4;
$substrLen = $endPos - $substrPos;
echo substr($input, $substrPos, $substrLen);
}
Output:
465.670
---
465.670
---
465.670
---
465.670
---
465.670
My string looks like this 05/21/2018 ghijkl 06/12/2018 mnopqrst
I need to extract all the values after each date and include the date. I tried
explode('/2018', $string);
But that splits up the date and is also not future-proof. I'm thinking there must be a way to include the delimiter in the element. Perhaps there is also a regular expression I should be using to find the date?
Thank you.
You could use preg_split with the PREG_SPLIT_DELIM_CAPTURE and the PREG_SPLIT_NO_EMPTY flags to keep the delimiter and remove the empty values from the resulting array.
You might use a pattern that matches a date format \b\d{1,2}/\d{1,2}/\d{4}\b (Note that it matches your date format in the example data and does not validate a date itself)
For example:
$str = '05/21/2018 ghijkl 06/12/2018 mnopqrst';
$result = preg_split('#(\b\d{1,2}/\d{1,2}/\d{4}\b)#', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($result);
Demo
To validate a date you could use DateTime and perhaps specify your format using createFromFormat.
$date = DateTime::createFromFormat("m/d/Y", '05/21/2018');
You can use current(explode('/', $string));
You can do something like this
$str = '05/21/2018 ghijkl 10/12/2017 mnopqrst';
$arr = explode(' ',$str);
$new = array();
for($i=0;$i<count($arr);$i+=2){
$new[] = ["date"=>$arr[$i],"value"=>$arr[$i+1]];
}
print_r($new);
Live Demo
Output:
Array
(
[0] => Array
(
[date] => 05/21/2018
[value] => ghijkl
)
[1] => Array
(
[date] => 10/12/2017
[value] => mnopqrst
)
)
Assuming your date is guaranteed to be formatted as you mentioned (if it's user input data, it's generally not safe to assume that), you could use a regular expression to find strings after a date:
Using a PHP regex split with the below expression:
/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4})([a-zA-Z\s]+)/g
Will break 05/21/2018 ghijkl 10/12/2017 mnopqrst into an array with the different groups. Depending how you actually want the output data, you can capture the date and subsequent string in one match group.
Sample code:
$string = '05/21/2018 ghijkl 10/12/2017 mnopqrst';
preg_split('/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4})([a-zA-Z\s]+)/g', $string, $stringParts);
array (
0 => '05/21/2018',
1 => 'ghijkl',
2 => '10/12/2017',
3 => 'mnopqrst'
);
https://regex101.com/r/gPXkDz/2
You could do that using regular expressions. Here's an example code:
<?php
$string = '05/21/2018 ghijkl 06/12/2018 mnopqrst';
$matches = [];
if (preg_match_all('#(\d{2}\/\d{2}\/\d{4})#i', $string, $matches) > 0) {
echo "Found the following dates: \n";
foreach ($matches[0] as $date) {
printf("- %s\n", $date);
}
}
This would result in the following output:
Found the following dates:
- 05/21/2018
- 06/12/2018
How would I use regular expression with PHP to split the following string into 2 pars as depicted below:
String to be split: 4x330ml
Split into 4x330 and ml
I have tried the following but it does not return the accurate data:
$pdata = "4x330ml"
$data = preg_split('#(?<=\d)(?=[a-z])#i', $pdata);
Then I get something like 4 in $data[0] and x330 in $data[1]
EDIT: Please note that ml could also be cm, kg, etc. A little complicated, which I don't seem to find a solution.
EDIT: Also I have tried the following regex (which I prefer to use at this point) with incomplete results:
$pdata = "5x500ml";
$data = preg_split('/(\d+\.?\d+)|(\w+)i/', $pdata);
This returns:
Array
(
[0] => 5x
[1] => ml
)
500 from that string is not being returned...
Thanks,
You said it could be ml, cm, or kg. and that you don't have to use regex. So, assuming it is always 2 characters at the end, a very simple way to do this would be:
$string = "4x330ml";
$part1 = substr($string, 0, -2); //returns 4x330
$part2 = substr($string, -2, 2); //returns "ml"
This ought to give you what you want.
$pdata = "4x330cm";
$data = preg_match('/([^(ml|cm|kg)]*)(ml|cm|kg)/', $pdata, $group);
echo $group[0].' ';
echo $group[1].' ';
echo $group[2].' ';
Use the preg_match function, and store the results into an array. The 0 index will return the entire matched string. The $group[1] will return just "4x330". The $group[2]$ will return just the "cm".
I'd use preg_match:
$pdata = "4x330ml";
preg_match('/(\d+x\d+)(.*)/',$pdata, $m);
print_r($m);
Output:
Array
(
[0] => 4x330ml
[1] => 4x330
[2] => ml
)
Assuming the units will always be 2 characters long you can use this
$pdata = "4x330ml";
$strNumber = substr($pdata, 0, strlen($pdata)-2);
$strUnit = substr($pdata, strlen($pdata)-2,2);
echo $strNumber; //returns 4x330
echo $strUnit; //returns ml
you can do this without a regex
$string = '4x330ml';
$splitPoint = strrpos($string,'m');
$firstPart = substr($string,0,$string); //gets 4x330
$secondPart = substr($string,$splitPoint); //gets ml
I was able to solve this problem by using the following code:
$data = "4x500ml";
$pdata = preg_split('/(\d+x\d+)/', $data, NULL, PREG_SPLIT_DELIM_CAPTURE);
Which now prints:
array(
[0] =>
[1] => 4x500
[2] => ml
)
It looks like it is capturing the delimeter as array[1] and since the delimeter is actually the first section of the string I want to split, it is fine for now, until I find a better solution.
Thank you all for trying.
I'm looking to split this string:
/server hostname:port username:password
into:
Array ( [0] => hostname
[1] => port
[2] => username:password )
I don't wish for /server to be stored.
Hostname, port, username and password will all vary in lengths.
I'm not sure if I should be using preg_split for this, and what the matching pattern should be?
Thanks
Exploding the string and splitting it's parts can get you what you need. Note that the example below does nothing to check the string is actually in that format. It would be wise to check that.
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
list($username,$password) = explode(':',$bits[2]);
Edit to create what you need:
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
$arr = array($hostname,$port,$bits[2]);
I wouldn't use regex for this, instead, try this
$str="/server hostname:port username:password";
$arr=explode(" ",$str);
$newarr=array(explode(":",$arr[1])[0],explode(":",$arr[1])[1],$arr[2]);
Here is a test for it
See explode function, it will do the job
Depending on the input format parse_url() could be an option.
$str = '/server hostname:port username:pa sword';
if(preg_match("|/server (.+):(.+) ([^:]+:.+)|", $str, $m)){
print_r($m);
}
I recommend preg_match(). For best performance, use negated character classes or limited character ranges to allow the regex engine to perform greedy/possessive matching.
Code: (Demo)
$string = '/server localhost:3306 root:some pass with spaces & a : colon';
preg_match('~/server ([^:]+):(\d+) (.+)~', $string, $m);
array_shift($m); // remove the fullstring match
var_export($m);
Output:
array (
0 => 'localhost',
1 => '3306',
2 => 'root:some pass with spaces & a : colon',
)
Hi all
how can i get number(positive num) from string,if string syntax is the following:
t_def_type_id_2 t_def_type_id_22 t_def_type_id_334
so,in the first string i want to get 1,and in the second i want to get 22 and in the third string i want to get 334 using preg_match_all or any other sutable php function
You can use the regex
\d+$
with preg_match
if there is only one number in the string, simply use \d+
Try this:
preg_match('/^\w+(\d+)$/U', $string, $match);
$value = (int) $match[1];
You can use
str_replace('t_def_type_id_','');
what about following code:
^[\d]+(\d+)$
You can use preg_replace():
$defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString);
$string = "t_def_type_id_2
t_def_type_id_22
t_def_type_id_334";
preg_match_all("#t_def_type_id_([0-9]+)#is", $string, $matches);
$matches = $matches[1];
print_r($matches);
Result:
Array
(
[0] => 2
[1] => 22
[2] => 334
)
If it's always the last thing in your string, then using a banal string function approach is possible and looks a bit compacter:
$num = ltrim(strrchr($string, "_"), "_");
You may use
^\w+(\d+)$
but I did not test
Here's my alternative solution.
$number = array_pop(explode('_', $string));