Pattern for splitting a string - php

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',
)

Related

PHP explode by date while keeping delimitter

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

Get clean ids by regex

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/

Split the output in PHP

I'm trying to use either split, preg_split, or explode to parse the following data into an array so that I can easily print and modify the data:
28782188 /var/opt
When I run
print_r(preg_split('/ /', $input));
All I get is
Array ( [0] => 28782796 /var/opt )
Is there a way to make php split with the whitespace that I'm getting from my du calls?
I think you want
preg_split('/\s+/',$input);
To split by any white-space character - du seperates with tabs (\t) if I remember right, although don't quote me on that...
EDIT Changed regex to one that works...
<?php
$value = '28782188 /var/opt';
$values = array();
//du might separate size and directory with **multiple** space/tabs
preg_match_all('/\w*\S[\w\/]*/', $value, $values, PREG_PATTERN_ORDER);
print_r($values);
// outputs: Array ( [0] => '28782188', [1] => '/var/opt' )
?>
Try print_r(explode(' ', $input)); to break input over whitespace.
Just use explode...
print_r(explode(' ', $input));

reqular exp to get last number from string

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));

How to extract parts using regular expression in PHP?

For example you have the following string:
$text = "word1:text1#atpart/foo/do/myfood$textfinal";
The function will work like:
$parts = array();
extract( $regular_exp, $text, $parts );
In the parts array we will get this:
$parts[0] = "word1";
$parts[1] = "text1";
$parts[2] = "atpart";
$parts[3] = "/foo/do/myfood";
$parts[4] = "textfinal";
Thanks!
This may not be what you are after, but the format you show looks almost like a URL with a username:password#domain authentication in front. If you can get the last $ to be served as a ?, it might be an idea to use parse_url() to parse it.
$string = "word1:text1#atpart/foo/do/myfood?textfinal"; // notice the ?
$string = "none://".$string; // We need to add a protocol for this to work
print_r (parse_url($string));
Result:
Array (
[scheme] => none
[host] => atpart
[user] => word1
[pass] => text1
[path] => /foo/do/myfood
[query] => textfinal )
the advantage of this would be that it's pretty flexible if one or more parts can be missing in the incoming data. If that's not an issue, a regex may be more convenient.
try
$parts = preg_split('/[:#\$]+/', $text);
Without more details, this matches the proposed example:
preg_match('#(.*?):(.*?)#(.*?)(/.*?)\$(.*)#', $text, $parts);
note that you will get the parts starting at index 1 instead of 0.
$delims=':#$';
$word = strtok('word1:text1#atpart/foo/do/myfood$textfinal',$delims);
while ( $word!==false ) {
foreach( explode('/',$word,2) as $tmp){
$words[]=$tmp;
}
$word = strtok($delims);
}
var_dump($words);
On one hand this is probably overkill. On the other hand, this may be more flexible depending on how different the string can be.
Demo: http://codepad.org/vy5b9yX7
Docs: http://php.net/strtok

Categories