Is it possible to convert the following string in to an array with PHP and preg_match_all, e.g;
The string will always be one character and a number followed by a space.
String: "C1 X2 B10"
$array[0][type]=>"C"
$array[0][number]=>1
$array[1][type]=>"X"
$array[1][number]=>2
$array[2][type]=>"B"
$array[2][number]=>10
You can use named groups in your regex:
$str = "C1 X2 B10";
$re = '~(?P<type>[A-Z])(?P<number>\d+)~';
preg_match_all($re, $str, $m, PREG_SET_ORDER);
print_r($m);
which gives you
Array
(
[0] => Array
(
[0] => C1
[type] => C
[1] => C
[number] => 1
[2] => 1
)
[1] => Array
(
[0] => X2
[type] => X
[1] => X
[number] => 2
[2] => 2
)
etc
so you can use $m[1]['type'] directly.
Of course, you can always use the regex for this which is WAAAAY faster, but I wanted to show you that you can do it without regex. There are more ways to solve a problem. As Harvey Specter, the character from "Suits" would say: "If someone points a gun to your head, there are 146 ways you can defend yourself" ;)
Here... try this:
$string = 'C1 X2 B10';
$explode = explode(' ', $string);
$i = 0;
foreach ($explode as $exp){
$number = substr($exp, 1);
$letter = substr($exp, 0, 1);
$array[$i]['type'] = $letter;
$array[$i]['number'] = $number;
$i++;
}
echo '<pre>';
print_r($array);
echo '</pre>';
the output will be:
Array
(
[0] => Array
(
[type] => C
[number] => 1
)
[1] => Array
(
[type] => X
[number] => 2
)
[2] => Array
(
[type] => B
[number] => 10
)
)
WARNING!! This solution will work only if you have only 1 letter, only at the beginning, with space separated elements in the string!
Hope this helps! :D
Related
I have a long string like this I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];. Now I just want to get certain words like 'I1','I2','I8','NA1' and so on i.e. words between ':'&';' only ,and store them in array. How to do that efficiently?
I have already tried using preg_split() and it works but giving me wrong output. As shown below.
// $a is the string I want to extract words from
$str = preg_split("/[;:]/", $a);
print_r($str);
The output I am getting is this
Array
(
[0] => I8
[1] => 2
[2] => I1
[3] => 1
[4] => I2
[5] => 2
[6] => I3
[7] => 2
[8] => I4
[9] => 4
[10] =>
)
Array
(
[0] => NA1
[1] => 5
[2] =>
)
Array
(
[0] => IA1
[1] => [1,2,3,4,5]
[2] =>
)
Array
(
[0] => S1
[1] => asadada
[2] =>
)
Array
(
[0] => SA1
[1] => [1,2,3,4,5]
[2] =>
)
But I am expecting 'I8','I1','I2','I3','I4' also in seperated array with position [0]. Any help on how to do this.
You could try something like.
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/(?:^|[;:])(\w+)/', $str, $result);
print_r($result[1]); // Matches are here in $result[1]
You can perform a greedy match to match the items between ; and : using preg_match_all()
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/;(.+?)\:/',$str,$matches);
print_r($matches[1]);
Live Demo: https://3v4l.org/eBsod
One possible approach is using a combination of explode() and implode(). The result is returned as a string, but you can easily put it into an array for example.
<?php
$input = "I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];.";
$output = array();
$array = explode(";", $input);
foreach($array as $item) {
$output[] = explode(":", $item)[0];
}
echo implode(",", $output);
?>
Output:
I1,I2,I8,NA1,IA1,S1,SA1,SA1,.
I'm facing a problem that I can't solve on my own, I can't find a way to do it.
I have those two strings:
'Germany, "Sightseeing, Travelling, Hotels"'
and
'Health, Medicin, Healthcare'
I need to explode() this strings on the , char, but only if the text, where this , lays in isn't surrounded by ".
So, as example this would be the desired results:
array(0 => 'Germany', 1 => '"Sightseeing, Travelling, Hotels"');
array(0 => 'Health', 1 => 'Medicin', 2 => 'Healthcare');
By now this is what I have:
explode(",", 'Germany, "Sightseeing, Travelling, Hotels"');
Which will give out
array(0 => 'Germany', 1 => '"Sightseeing', 2 => 'Travelling', 3 => 'Hotels"');
How can I get to this result?
See str_getcsv() how to parse csv (even if you are not reading a csv file, this is exactly what this string looks like):
<?php
print_r(str_getcsv('Germany, "Sightseeing, Travelling, Hotels"', ','));
print_r(str_getcsv('Health, Medicin, Healthcare'));
print_r(str_getcsv('D"uh!, \"Test\"', ','));
?>
results in:
Array ( [0] => Germany [1] => Sightseeing, Travelling, Hotels )
Array ( [0] => Health [1] => Medicin [2] => Healthcare )
Array ( [0] => D"uh! [1] => "Test" )
Remarks: This Function is available beginning with php version 5.3.0 and can also be configured as to what your input looks like. I added some special cases, this is a classic problem that looks far simpler than it is.
You can use php function str_getcsv.
Here an example:
$string_1 = 'Germany, "Sightseeing, Travelling, Hotels"';
$string_2 = 'Health, Medicin, Healthcare';
$result_1 = str_getcsv($string_1,',','"');
$result_2 = str_getcsv($string_2,',','"');
print_R($result_1);
print_R($result_2);
that outputs:
Array
(
[0] => Germany
[1] => Sightseeing, Travelling, Hotels
)
Array
(
[0] => Health
[1] => Medicin
[2] => Healthcare
)
You can after map each element of the resultant array, and if there is a comma you can surround it with "
foreach($result_1 as $i => $item) {
if(substr_count($item,',') > 0) {
$result_1[$i] = '"'.$item.'"';
}
}
Wich produce:
Array
(
[0] => Germany
[1] => "Sightseeing, Travelling, Hotels"
)
I have a string:
xyz.com?username="test"&pwd="test"#score="score"#key="1234"
output format:
array (
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)
This should work for you:
Just use preg_split() with a character class with all delimiters in it. At the end just use array_shift() to remove the first element.
<?php
$str = 'xyz.com?username="test"&pwd="test"#score="score"#key="1234"';
$arr = preg_split("/[?&##]/", $str);
array_shift($arr);
print_r($arr);
?>
output:
Array
(
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)
You can use preg_split function with regex pattern including all those delimimting special characters. Then remove the first value of the array and reset keys:
$s = 'xyz.com?username="test"&pwd="test"#score="score"#key="1234"';
$a = preg_split('/[?&##]/',$s);
unset($a[0]);
$a = array_values($a);
print_r($a);
Output:
Array (
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)
I'm looking how I can explode a string that where the delimiter is repeated successively but I didn't find the solution.
The string is: $text = "43##567#####152990#572##017"; and I want to get the numbers in an array().
I tried with explode() and putting the + as delimiter but it returns empty positions.
$res = preg_split('/\#+/', '43##567#####152990#572##017');
print_r($res);
OUTPUT:
Array
(
[0] => 43
[1] => 567
[2] => 152990
[3] => 572
[4] => 017
)
<?php
$text = "43##567#####152990#572##017";
$data = array_filter(explode('#',$text));
print_r($data);
?>
please note that it will remove zeroes aswell...
Easy. Just use preg_split like this:
$data = "43##567#####152990#572##017";
$split_data = preg_split("/#?#+/is", $data, -1, null);
echo '<pre>';
print_r($split_data);
echo '</pre>';
And the results would be:
Array
(
[0] => 43
[1] => 567
[2] => 152990
[3] => 572
[4] => 017
)
I have a string and I would like to explode with three differents patterns. The string looks like to :
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
I would like to get the differents parts of this two strings. The two lines are separated by a /n, the dates are separated by : and the link associated to date are separated with a ->
At the beginning I explode by the line break
$var = explode("\n", $var);
but when I tried to explode again this string, I get an error : *preg_split() expects parameter 2 to be string, array given*
How can I get the different parts ?
Thanks in advance.
Ideone link
Instead of using preg_split, consider using preg_match. You can write it as one big regex.
<?php
// Implicit newline. Adding \n would make an empty spot in the array
$str = "country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4";
$arr = split("\n", $str);
for ($i = 0; $i < count($arr); $i++) {
preg_match("/^(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)/", $arr[$i], $matches);
print_r($matches);
}
?>
Output:
Array
(
[0] => country:00/00/00->link:00/00/00->link2
[1] => country
[2] => 00/00/00
[3] => link
[4] => 00/00/00
[5] => link2
)
Array
(
[0] => country2:00/00/00->link3:00/00/00->link4
[1] => country2
[2] => 00/00/00
[3] => link3
[4] => 00/00/00
[5] => link4
)
EDIT
In your comment, you're posting dates with 4 digits, whereas in your question, they only had 2 digits.
Therefore you need to change the regex to:
/^(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)/
How about using preg_match_all:
<?php
$data =<<<ENDDATA
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
ENDDATA;
preg_match_all('#(\d{2}/\d{2}/\d{2})->(.[^:\n]+)#', $data, $matches);
print_r($matches);
Gives the following result:
Array
(
[0] => Array
(
[0] => 00/00/00->link
[1] => 00/00/00->link2
[2] => 00/00/00->link3
[3] => 00/00/00->link4
)
[1] => Array
(
[0] => 00/00/00
[1] => 00/00/00
[2] => 00/00/00
[3] => 00/00/00
)
[2] => Array
(
[0] => link
[1] => link2
[2] => link3
[3] => link4
)
)
your problem is that after using explode first time, it is turning into an array and explode function connat explode an array. You need to use a loop probablr for loop that targets array elemets then use explode function on those elements and you will have it.
See example Below:
<?php
$val="abc~~~def~~~ghi####jkl~~~mno~~~pqr###stu~~~vwx~~~yz1";
$val=explode("####", $val);
//result will be
$valWillBe=array(3) {
[0]=>'abc~~~def~~~ghi',
[1]=>'jkl~~~mno~~~pqr',
[2]=>'stu~~~vwx~~~yz1'
}
//if you want to explode again you use a loop
for($r=0; $r<sizeof($val); $r++){
$val[$r]=explode("~~~", $val[$r]);
}
//now you have your string exploded all in places.
?>